Exemple #1
0
        public bool load_vpc_id()
        {
            write_log(region + " の VPC を確認しています。");
            try
            {
                var client    = get_client();
                var query_req = new DescribeVpcsRequest();
                query_req.Filters.Add(new Filter()
                {
                    Name = "tag-value", Values = new List <string>()
                    {
                        Helper.build_name(setting_, "vpc")
                    }
                });
                var query_res = client.DescribeVpcs(query_req);
                if (query_res.Vpcs.Count != 0)
                {
                    vpc_id = query_res.Vpcs[0].VpcId;
                    return(true);
                }

                write_log(region + " に VPC を作成しています。");
                var create_req = new CreateVpcRequest();
                create_req.CidrBlock = "10.0.0.0/16";
                var create_res = client.CreateVpc(create_req);
                set_name_tag(client, create_res.Vpc.VpcId, Helper.build_name(setting_, "vpc"));
                vpc_id = create_res.Vpc.VpcId;
            }
            catch (Exception ex)
            {
                write_log("ERROR: " + ex.ToString());
                return(false);
            }
            return(true);
        }
        private async Task <Vpc> VpcExists()
        {
            var request  = new DescribeVpcsRequest();
            var response = await _client.DescribeVpcsAsync(request);

            return(response.Vpcs.FirstOrDefault(vpc => vpc.CidrBlock == _cluster.VpcCidr));
        }
Exemple #3
0
        public bool check_vpc_id()
        {
            write_log(region + " の VPC を確認しています。");
            try
            {
                var client    = get_client();
                var query_req = new DescribeVpcsRequest();
                query_req.Filters.Add(new Filter()
                {
                    Name = "tag-value", Values = new List <string>()
                    {
                        Helper.build_name(setting_, "vpc")
                    }
                });
                var query_res = client.DescribeVpcs(query_req);
                if (query_res.Vpcs.Count == 0)
                {
                    return(false);
                }

                vpc_id = query_res.Vpcs[0].VpcId;
            }
            catch (Exception ex)
            {
                write_log("ERROR: " + ex.ToString());
                return(false);
            }
            return(true);
        }
Exemple #4
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonEC2Config config = new AmazonEC2Config();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonEC2Client client = new AmazonEC2Client(creds, config);

            DescribeVpcsResponse resp = new DescribeVpcsResponse();

            do
            {
                DescribeVpcsRequest req = new DescribeVpcsRequest
                {
                    NextToken = resp.NextToken
                    ,
                    MaxResults = maxItems
                };

                resp = client.DescribeVpcs(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Vpcs)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextToken));
        }
        public IEnumerable <Vpc> GetVpcs()
        {
            var request  = new DescribeVpcsRequest();
            var response = _ec2Client.DescribeVpcs(request);

            return(response.Vpcs);
        }
        internal List <Vpc> getVPCbyId(string VpcId)
        {
            DescribeVpcsRequest req = new DescribeVpcsRequest();

            req.Filters.Add(new Filter()
            {
                Name   = "vpc-id",
                Values = new List <string>()
                {
                    VpcId
                }
            }); return(_service.DescribeVpcs(req).Vpcs);
        }
Exemple #7
0
        public void TestDescribeVpcs()
        {
            //vpc-zo33sfjnbo
            VpcClient           vpcClient = GetVpcClient();
            DescribeVpcsRequest request   = new DescribeVpcsRequest();

            request.RegionId   = "cn-north-1";
            request.PageNumber = 1;
            request.PageSize   = 100;
            var result = vpcClient.DescribeVpcs(request).Result;

            _output.WriteLine(JsonConvert.SerializeObject(result));
        }
Exemple #8
0
        private static DescribeVpcsResponse DescribeVpcsByTag()
        {
            var describeVpcsRequest = new DescribeVpcsRequest
            {
                Filters = new List <Filter>
                {
                    new Filter("tag:" + DotNetTag.Key, new List <string> {
                        DotNetTag.Value
                    })
                }
            };

            return(Client.DescribeVpcs(describeVpcsRequest));
        }
Exemple #9
0
        public async Task <List <Vpc> > DescribeVpcs()
        {
            DescribeVpcsRequest request = new DescribeVpcsRequest();

            DescribeVpcsResponse response = await _ec2Client.DescribeVpcsAsync();

            List <Vpc> vpcs = new List <Vpc>();

            foreach (var vpc in response.Vpcs)
            {
                vpcs.Add(new Vpc(vpc.VpcId, vpc.OwnerId, vpc.CidrBlock));
            }
            return(vpcs);
        }
        private async Task <string> GetVpcId()
        {
            var request = new DescribeVpcsRequest
            {
                VpcIds = { _cluster.VpcCidr }
            };

            var response = await _client.DescribeVpcsAsync(request);

            var vpc = response.Vpcs.FirstOrDefault();

            if (vpc == null)
            {
                throw new InvalidOperationException($"Vpc not found: {_cluster.VpcCidr}");
            }
            return(vpc.VpcId);
        }
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonEC2Config config = new AmazonEC2Config();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonEC2Client client = new AmazonEC2Client(creds, config);

            DescribeVpcsResponse resp = new DescribeVpcsResponse();
            DescribeVpcsRequest  req  = new DescribeVpcsRequest
            {
            };

            resp = client.DescribeVpcs(req);
            CheckError(resp.HttpStatusCode, "200");

            foreach (var obj in resp.Vpcs)
            {
                AddObject(obj);
            }
        }
Exemple #12
0
        public static List <TcsData.Vpc> GetVpcs()
        {
            IAmazonEC2          ec2        = AWSClientFactory.CreateAmazonEC2Client();
            DescribeVpcsRequest vpcRequest = new DescribeVpcsRequest();
            var vpcList = new List <TcsData.Vpc>();

            try
            {
                DescribeVpcsResponse ec2Response = ec2.DescribeVpcs(vpcRequest);
                int numVpcs = 0;
                numVpcs = ec2Response.Vpcs.Count;
                foreach (var vpc in ec2Response.Vpcs)
                {
                    var tcsVpc = new TcsData.Vpc();
                    //tcsVpc.AvailableVolumes = vpc.
                }
            }
            catch (AmazonEC2Exception ex)
            {
            }
            return(vpcList);
        }
Exemple #13
0
        /****************************************** VPC  ******************************************/
        public async Task <List <SA_Vpc> > GetVPCList()
        {
            var request  = new DescribeVpcsRequest();
            var response = await client.DescribeVpcsAsync(request);

            var ret = new List <SA_Vpc>();

            foreach (var vpc in response.Vpcs)
            {
                if (vpc.IsDefault)
                {
                    continue;
                }
                ret.Add(new SA_Vpc()
                {
                    CidrBlock = vpc.CidrBlock,
                    Name      = vpc.Tags.Find(o => o.Key == "Name").Value,
                    State     = vpc.State,
                    VpcId     = vpc.VpcId
                });
            }
            return(ret);
        }
Exemple #14
0
        internal void LaunchServer(ref bool actionSucceeded, ref string actionMessage)
        {
            try
            {
                string keyPairPath = string.Empty;
                LaunchRequest.KeyPairName = $"KeyPair-{Guid.NewGuid().ToString()}";
                while (!CreateKeyPair(LaunchRequest.KeyPairName, ref keyPairPath))
                {
                    LaunchRequest.KeyPairName = Guid.NewGuid().ToString();
                }

                DescribeVpcsRequest  vpcRequest  = new DescribeVpcsRequest();
                DescribeVpcsResponse vpcResponse = Ec2Client.DescribeVpcsAsync(vpcRequest).GetAwaiter().GetResult();

                Vpc defaultVPC = vpcResponse.Vpcs.Find(x => x.IsDefault); //get the default vpc

                List <Filter> subnetFilter = new List <Filter>()
                {
                    new Filter()
                    {
                        Name = "availability-zone", Values = new List <string>()
                        {
                            LaunchRequest.AvailabilityZone
                        }
                    },
                    new Filter()
                    {
                        Name = "vpc-id", Values = new List <string>()
                        {
                            defaultVPC.VpcId
                        }
                    }
                };

                DescribeSubnetsRequest subnetRequest = new DescribeSubnetsRequest();
                subnetRequest.Filters = subnetFilter;
                DescribeSubnetsResponse subnetResponse = Ec2Client.DescribeSubnetsAsync(subnetRequest).GetAwaiter().GetResult();
                Subnet defaultSubnet = subnetResponse.Subnets.FirstOrDefault();

                Filter SGFilter = new Filter
                {
                    Name   = "vpc-id",
                    Values = new List <string>()
                    {
                        defaultVPC.VpcId
                    }
                };

                DescribeSecurityGroupsRequest SGrequest = new DescribeSecurityGroupsRequest();
                SGrequest.Filters.Add(SGFilter);
                DescribeSecurityGroupsResponse SGresponse = Ec2Client.DescribeSecurityGroupsAsync(SGrequest).GetAwaiter().GetResult();
                SecurityGroup defaultSG = SGresponse.SecurityGroups.FirstOrDefault();

                InstanceNetworkInterfaceSpecification defaultENI = new InstanceNetworkInterfaceSpecification()
                {
                    DeviceIndex = 0,
                    SubnetId    = defaultSubnet.SubnetId,
                    Groups      = new List <string>()
                    {
                        defaultSG.GroupId
                    },
                    AssociatePublicIpAddress = true
                };

                List <InstanceNetworkInterfaceSpecification> enis = new List <InstanceNetworkInterfaceSpecification>()
                {
                    defaultENI
                };

                EbsBlockDevice ebsBlockDevice = new EbsBlockDevice
                {
                    VolumeSize = 10,
                    VolumeType = GetActualStorageType(LaunchRequest.StorageType)
                };
                BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping
                {
                    DeviceName = "/dev/xvda"
                };
                blockDeviceMapping.Ebs = ebsBlockDevice;

                var launchRequest = new RunInstancesRequest()
                {
                    ImageId             = GetImageID(LaunchRequest.AMIType),
                    InstanceType        = GetActualInstanceType(LaunchRequest.InstanceType),
                    MinCount            = LaunchRequest.NumOfInstances,
                    MaxCount            = LaunchRequest.NumOfInstances,
                    KeyName             = LaunchRequest.KeyPairName,
                    Placement           = new Placement(LaunchRequest.AvailabilityZone),
                    NetworkInterfaces   = enis,
                    BlockDeviceMappings = new List <BlockDeviceMapping>()
                    {
                        blockDeviceMapping
                    }
                };

                RunInstancesResponse launchResponse = Ec2Client.RunInstancesAsync(launchRequest).GetAwaiter().GetResult();

                List <String> instanceIds = new List <string>();
                foreach (Instance instance in launchResponse.Reservation.Instances)
                {
                    Console.WriteLine(instance.InstanceId);
                    instanceIds.Add(instance.InstanceId);
                }

                actionSucceeded = true;
                actionMessage   = $"The instance(s) are being launched. Please check the AWS Console to verify. {keyPairPath}";
            }
            catch (Exception ex)
            {
                context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.Message}");
                context.Logger.LogLine($"ServerOperationsHelper::LaunchServer {ex.StackTrace}");
                actionSucceeded = false;
                actionMessage   = $"Could not launch the server . Please contact your administrator.";
            }
        }
        /// <summary>
        /// This method will create a VPC with a subnet that will have an internet gateway attached making instances available to the internet.
        /// </summary>
        /// <param name="ec2Client">The ec2client used to create the VPC</param>
        /// <param name="request">The properties used to create the VPC.</param>
        /// <param name="response">The response contains all the VPC objects that were created.</param>
        private static void LaunchVPCWithPublicSubnet(IAmazonEC2 ec2Client, LaunchVPCWithPublicSubnetRequest request, LaunchVPCWithPublicSubnetResponse response)
        {
            response.VPC = ec2Client.CreateVpc(new CreateVpcRequest()
            {
                CidrBlock       = request.VPCCidrBlock,
                InstanceTenancy = request.InstanceTenancy
            }).Vpc;
            WriteProgress(request.ProgressCallback, "Created vpc {0}", response.VPC.VpcId);

            var describeVPCRequest = new DescribeVpcsRequest()
            {
                VpcIds = new List <string>()
                {
                    response.VPC.VpcId
                }
            };

            WaitTillTrue(((Func <bool>)(() => ec2Client.DescribeVpcs(describeVPCRequest).Vpcs.Count == 1)));

            if (!string.IsNullOrEmpty(request.VPCName))
            {
                ec2Client.CreateTags(new CreateTagsRequest()
                {
                    Resources = new List <string>()
                    {
                        response.VPC.VpcId
                    },
                    Tags = new List <Tag>()
                    {
                        new Tag()
                        {
                            Key = "Name", Value = request.VPCName
                        }
                    }
                });
            }

            response.PublicSubnet = ec2Client.CreateSubnet(new CreateSubnetRequest()
            {
                AvailabilityZone = request.PublicSubnetAvailabilityZone,
                CidrBlock        = request.PublicSubnetCiderBlock,
                VpcId            = response.VPC.VpcId
            }).Subnet;
            WriteProgress(request.ProgressCallback, "Created public subnet {0}", response.PublicSubnet.SubnetId);

            WaitTillTrue(((Func <bool>)(() => (ec2Client.DescribeSubnets(new DescribeSubnetsRequest()
            {
                SubnetIds = new List <string>()
                {
                    response.PublicSubnet.SubnetId
                }
            }).Subnets.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                Resources = new List <string>()
                {
                    response.PublicSubnet.SubnetId
                },
                Tags = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "Public"
                    }
                }
            });

            response.InternetGateway = ec2Client.CreateInternetGateway(new CreateInternetGatewayRequest()
            {
            }).InternetGateway;
            WriteProgress(request.ProgressCallback, "Created internet gateway {0}", response.InternetGateway.InternetGatewayId);

            ec2Client.AttachInternetGateway(new AttachInternetGatewayRequest()
            {
                InternetGatewayId = response.InternetGateway.InternetGatewayId,
                VpcId             = response.VPC.VpcId
            });
            WriteProgress(request.ProgressCallback, "Attached internet gateway to vpc");

            response.PublicSubnetRouteTable = ec2Client.CreateRouteTable(new CreateRouteTableRequest()
            {
                VpcId = response.VPC.VpcId
            }).RouteTable;
            WriteProgress(request.ProgressCallback, "Created route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            var describeRouteTableRequest = new DescribeRouteTablesRequest()
            {
                RouteTableIds = new List <string>()
                {
                    response.PublicSubnetRouteTable.RouteTableId
                }
            };

            WaitTillTrue(((Func <bool>)(() => (ec2Client.DescribeRouteTables(describeRouteTableRequest).RouteTables.Count == 1))));

            ec2Client.CreateTags(new CreateTagsRequest()
            {
                Resources = new List <string>()
                {
                    response.PublicSubnetRouteTable.RouteTableId
                },
                Tags = new List <Tag>()
                {
                    new Tag()
                    {
                        Key = "Name", Value = "Public"
                    }
                }
            });

            ec2Client.AssociateRouteTable(new AssociateRouteTableRequest()
            {
                RouteTableId = response.PublicSubnetRouteTable.RouteTableId,
                SubnetId     = response.PublicSubnet.SubnetId
            });
            WriteProgress(request.ProgressCallback, "Associated route table to public subnet");

            ec2Client.CreateRoute(new CreateRouteRequest()
            {
                DestinationCidrBlock = "0.0.0.0/0",
                GatewayId            = response.InternetGateway.InternetGatewayId,
                RouteTableId         = response.PublicSubnetRouteTable.RouteTableId
            });
            WriteProgress(request.ProgressCallback, "Added route for internet gateway to route table {0}", response.PublicSubnetRouteTable.RouteTableId);

            response.PublicSubnetRouteTable = ec2Client.DescribeRouteTables(describeRouteTableRequest).RouteTables[0];
        }
Exemple #16
0
        public bool delete_vpc_all(string region_txt)
        {
            try
            {
                var client = get_client();
                write_log(region + " の VPC を確認しています。");
                var query_req = new DescribeVpcsRequest();
                query_req.Filters.Add(new Filter()
                {
                    Name = "tag-value", Values = new List <string>()
                    {
                        Helper.build_name(setting_, "vpc")
                    }
                });
                var query_res = client.DescribeVpcs(query_req);
                if (query_res.Vpcs.Count == 0)
                {
                    write_log(region + " の VPC が存在しませんでした。");
                    return(true);
                }
                vpc_id = query_res.Vpcs[0].VpcId;

                var query_instance_req = new DescribeInstancesRequest();
                var query_instance_res = client.DescribeInstances(query_instance_req);

                bool flg = true;
                foreach (var row in query_instance_res.Reservations)
                {
                    foreach (var row2 in row.Instances)
                    {
                        if (row2.State != null && row2.State.Code != 48 &&
                            row2.VpcId != null && row2.VpcId.Equals(vpc_id))
                        {
                            flg = false;
                            break;
                        }
                    }
                    if (flg == false)
                    {
                        break;
                    }
                }
                if (flg == false)
                {
                    write_log(region + " にはインスタンスが存在する為、VPC を削除できません。");
                    return(false);
                }

                write_log(region + " のセキュリティグループを確認しています。");

                var query_sg_req = new DescribeSecurityGroupsRequest();
                query_sg_req.Filters.Add(new Filter()
                {
                    Name = "tag-value", Values = new List <string>()
                    {
                        Helper.build_name(setting_, "sg")
                    }
                });
                var query_sg_res = client.DescribeSecurityGroups(query_sg_req);
                foreach (var row in query_sg_res.SecurityGroups)
                {
                    write_log("セキュリティグループ " + row.GroupId + " を削除しています。");
                    var delete_sg_req = new DeleteSecurityGroupRequest();
                    delete_sg_req.GroupId = row.GroupId;
                    client.DeleteSecurityGroup(delete_sg_req);
                }

                using (FileStream fs = new FileStream(region_txt, FileMode.Open, FileAccess.Read))
                {
                    IList <string> list = new List <string>(subnet_ids.Keys);
                    foreach (string tag in list)
                    {
                        if (Helper.check_az(fs, region, tag, 0) == false)
                        {
                            continue;
                        }
                        write_log(region + tag + " のサブネットを確認しています。");
                        var query_sub_req = new DescribeSubnetsRequest();
                        query_sub_req.Filters.Add(new Filter()
                        {
                            Name = "tag-value", Values = new List <string>()
                            {
                                Helper.build_name(setting_, "subnet_" + tag)
                            }
                        });
                        var query_sub_res = client.DescribeSubnets(query_sub_req);
                        foreach (var row in query_sub_res.Subnets)
                        {
                            write_log("サブネット " + row.SubnetId + " を削除しています。");
                            var delete_sub_req = new DeleteSubnetRequest();
                            delete_sub_req.SubnetId = row.SubnetId;
                            client.DeleteSubnet(delete_sub_req);
                        }
                    }
                }

                write_log(region + " のインターネットゲートウェイを確認しています。");

                var query_igw_req = new DescribeInternetGatewaysRequest();
                query_igw_req.Filters.Add(new Filter()
                {
                    Name = "tag-value", Values = new List <string>()
                    {
                        Helper.build_name(setting_, "igw")
                    }
                });
                var query_igw_res = client.DescribeInternetGateways(query_igw_req);
                foreach (var row in query_igw_res.InternetGateways)
                {
                    var detach_igw_req = new DetachInternetGatewayRequest();
                    detach_igw_req.InternetGatewayId = row.InternetGatewayId;
                    detach_igw_req.VpcId             = vpc_id;
                    client.DetachInternetGateway(detach_igw_req);

                    var delete_igw_req = new DeleteInternetGatewayRequest();
                    delete_igw_req.InternetGatewayId = row.InternetGatewayId;
                    client.DeleteInternetGateway(delete_igw_req);
                }

                write_log("VPC " + vpc_id + " を削除しています。");

                var delete_vpc_req = new DeleteVpcRequest();
                delete_vpc_req.VpcId = vpc_id;
                client.DeleteVpc(delete_vpc_req);
            }
            catch (Exception ex)
            {
                write_log("ERROR: " + ex.ToString());
                return(false);
            }
            return(true);
        }