private void Go_Window2() { if (inputsAreValid(source2_CB, profile2_CB, templateOrStack2_TB, validation2_LB)) { AmazonCloudFormationClient CFclient = null; AmazonEC2Client EC2client = null; StackOriginal2 = new CFStack(); StackCopy2 = new CFStack(); try { profileName2 = profile2_CB.Text; if (validateTemplate_CB.Checked || source2_CB.Text == "AWS") { var creds = new StoredProfileAWSCredentials(profileName2); CFclient = new AmazonCloudFormationClient(creds); EC2client = new AmazonEC2Client(creds); } switch (source2_CB.Text) { case "Template": templatePath2 = templateOrStack2_TB.Text.Trim(); using (StreamReader sr = new StreamReader(templatePath2)) { jasonString2 = sr.ReadToEnd(); if (validateTemplate_CB.Checked) { if (validateTemplate(jasonString2, CFclient)) { ProcessTemplate(jasonString2, richTextBox2, templatePath2, StackOriginal2); } } else { ProcessTemplate(jasonString2, richTextBox2, templatePath2, StackOriginal2); } } break; case "AWS": stackName2 = templateOrStack2_TB.Text.Trim(); ProcessLiveStack(stackName2, CFclient, EC2client, richTextBox2, StackOriginal2); break; } profileName2 = profile2_CB.Text.Trim(); } catch (Exception ex) { richTextBox2.Text = ex.Message; } finally { if (CFclient != null) { CFclient.Dispose(); } if (EC2client != null) { EC2client.Dispose(); } } } }
//public static void Main(string[] args) //{ // Console.Write(GetServiceOutput()); // Console.Read(); //} public static string GetServiceOutput() { StringBuilder sb = new StringBuilder(1024); using (StringWriter sr = new StringWriter(sb)) { sr.WriteLine("==========================================="); sr.WriteLine("Welcome to the AWS .NET SDK!"); sr.WriteLine("==========================================="); // Print the number of Amazon EC2 instances. IAmazonEC2 ec2 = new AmazonEC2Client(); DescribeInstancesRequest ec2Request = new DescribeInstancesRequest(); try { DescribeInstancesResponse ec2Response = ec2.DescribeInstances(ec2Request); int numInstances = 0; numInstances = ec2Response.Reservations.Count; sr.WriteLine(string.Format("You have {0} Amazon EC2 instance(s) running in the {1} region.", numInstances, ConfigurationManager.AppSettings["AWSRegion"])); } catch (AmazonEC2Exception ex) { if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure")) { sr.WriteLine("The account you are using is not signed up for Amazon EC2."); sr.WriteLine("You can sign up for Amazon EC2 at http://aws.amazon.com/ec2"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("Error Type: " + ex.ErrorType); sr.WriteLine("Request ID: " + ex.RequestId); } } sr.WriteLine(); // Print the number of Amazon SimpleDB domains. IAmazonSimpleDB sdb = new AmazonSimpleDBClient(); ListDomainsRequest sdbRequest = new ListDomainsRequest(); try { ListDomainsResponse sdbResponse = sdb.ListDomains(sdbRequest); int numDomains = 0; numDomains = sdbResponse.DomainNames.Count; sr.WriteLine(string.Format("You have {0} Amazon SimpleDB domain(s) in the {1} region.", numDomains, ConfigurationManager.AppSettings["AWSRegion"])); } catch (AmazonSimpleDBException ex) { if (ex.ErrorCode != null && ex.ErrorCode.Equals("AuthFailure")) { sr.WriteLine("The account you are using is not signed up for Amazon SimpleDB."); sr.WriteLine("You can sign up for Amazon SimpleDB at http://aws.amazon.com/simpledb"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("Error Type: " + ex.ErrorType); sr.WriteLine("Request ID: " + ex.RequestId); } } sr.WriteLine(); // Print the number of Amazon S3 Buckets. IAmazonS3 s3Client = new AmazonS3Client(); try { ListBucketsResponse response = s3Client.ListBuckets(); int numBuckets = 0; if (response.Buckets != null && response.Buckets.Count > 0) { numBuckets = response.Buckets.Count; } sr.WriteLine("You have " + numBuckets + " Amazon S3 bucket(s)."); } catch (AmazonS3Exception ex) { if (ex.ErrorCode != null && (ex.ErrorCode.Equals("InvalidAccessKeyId") || ex.ErrorCode.Equals("InvalidSecurity"))) { sr.WriteLine("Please check the provided AWS Credentials."); sr.WriteLine("If you haven't signed up for Amazon S3, please visit http://aws.amazon.com/s3"); } else { sr.WriteLine("Caught Exception: " + ex.Message); sr.WriteLine("Response Status Code: " + ex.StatusCode); sr.WriteLine("Error Code: " + ex.ErrorCode); sr.WriteLine("Request ID: " + ex.RequestId); } } sr.WriteLine("Press any key to continue..."); } return(sb.ToString()); }
private void Go_Window1() { if (inputsAreValid(source1_CB, profile1_CB, templateOrStack1_TB, validation1_LB)) { AmazonCloudFormationClient CFclient = null; AmazonEC2Client EC2client = null; StackOriginal1 = new CFStack(); StackCopy1 = new CFStack(); try { profileName1 = profile1_CB.Text; if (validateTemplate_CB.Checked || source1_CB.Text == "AWS") { var creds = new StoredProfileAWSCredentials(profileName1); CFclient = new AmazonCloudFormationClient(creds); EC2client = new AmazonEC2Client(creds); } switch (source1_CB.Text) { case "Template": templatePath1 = templateOrStack1_TB.Text.Trim(); using (StreamReader sr = new StreamReader(templatePath1)) { jasonString1 = sr.ReadToEnd(); if (validateTemplate_CB.Checked) { if (validateTemplate(jasonString1, CFclient)) { ProcessTemplate(jasonString1, richTextBox1, templatePath1, StackOriginal1); } } else { ProcessTemplate(jasonString1, richTextBox1, templatePath1, StackOriginal1); } } break; case "AWS": stackName1 = templateOrStack1_TB.Text.Trim(); ProcessLiveStack(stackName1, CFclient, EC2client, richTextBox1, StackOriginal1); break; } profileName1 = profile1_CB.Text.Trim(); } catch (Exception ex) { richTextBox1.Text = ex.Message + Environment.NewLine + ex.StackTrace; } finally { if (CFclient != null) { CFclient.Dispose(); } if (EC2client != null) { EC2client.Dispose(); } } } }
// ----------------------------------------------------------------------- // Live Stack public static void ProcessNetworkAclFromAWS(StackResourceSummary resource, CFStack stack, AmazonEC2Client ec2Client, string stackName) { DescribeNetworkAclsRequest naclRequest = new DescribeNetworkAclsRequest(); naclRequest.NetworkAclIds = new List <string> { resource.PhysicalResourceId }; DescribeNetworkAclsResponse response = ec2Client.DescribeNetworkAcls(naclRequest); foreach (Amazon.EC2.Model.NetworkAcl nacl in response.NetworkAcls) { NetworkAcl n = new NetworkAcl(); n.LogicalId = resource.LogicalResourceId; if (log) { Utils.WriteToFile(logFile, "AWS NACL: " + n.LogicalId.ToString(), true); } n.Type = "AWS::EC2::NetworkAcl"; n.Properties.VpcId = nacl.VpcId; foreach (Amazon.EC2.Model.NetworkAclEntry e in nacl.Entries) { NetworkAclEntry ne = new NetworkAclEntry(); ne.RuleNumber = e.RuleNumber.ToString(); ne.CidrBlock = e.CidrBlock; ne.Egress = e.Egress; if (e.PortRange == null) { ne.FromPort = "ALL"; ne.ToPort = "ALL"; } else { //FormatPortRange - Port range could be 0-0 -1-1 0-65535 string from = ""; string to = ""; FormatPortRange(e.PortRange.From.ToString(), e.PortRange.To.ToString(), out from, out to); ne.FromPort = from; ne.ToPort = to; //------------------------------------------------------ } //FormatProtocol - Protocol could be a number or text (e.g. 6 or tcp) ne.Protocol = FormatProtocol(e.Protocol); //------------------------------------------------------------------- ne.RuleAction = e.RuleAction; //ICMP not included. n.Properties.NetworkAclEntry.Add(ne); if (e.PortRange == null) { if (log) { Utils.WriteToFile(logFile, ne.RuleNumber + " Protocol: " + e.Protocol + " | From: " + "null" + " To: " + "null", true); } } else { if (log) { Utils.WriteToFile(logFile, ne.RuleNumber + " Protocol: " + e.Protocol + " | From: " + e.PortRange.From.ToString() + " To: " + e.PortRange.To.ToString(), true); } } } stack.Resources.Add(n); } }
public static void ProcessEC2SecurityGroupFromAWS(StackResourceSummary resource, CFStack stack, AmazonEC2Client ec2Client, Dictionary <string, string> secGroupMap, string stackName) { DescribeSecurityGroupsRequest secGroupRequest = new DescribeSecurityGroupsRequest(); //Set request to use Phisical Id secGroupRequest.GroupIds = new List <string> { resource.PhysicalResourceId }; //Attempt to get security group using physical Id DescribeSecurityGroupsResponse response = GetSecurityGroup(ec2Client, secGroupRequest); if (response == null) { //Set request to use Logical Id and Stack Name Tags secGroupRequest.GroupIds.Clear(); List <Filter> f = new List <Filter>(); f.Add(new Filter { Name = "tag:aws:cloudformation:logical-id", Values = new List <string>() { resource.LogicalResourceId } }); f.Add(new Filter { Name = "tag:aws:cloudformation:stack-name", Values = new List <string>() { stackName } }); secGroupRequest.Filters = f; //Attempt to get security group using logical Id response = GetSecurityGroup(ec2Client, secGroupRequest); } if (response == null | response.SecurityGroups.Count == 0) { return; } foreach (SecurityGroup group in response.SecurityGroups) { EC2SecurityGroup sg = new EC2SecurityGroup(); sg.LogicalId = resource.LogicalResourceId; if (log) { Utils.WriteToFile(logFile, "AWS SG: " + sg.LogicalId.ToString(), true); } sg.Type = "AWS::EC2::SecurityGroup"; sg.Properties.GroupDescription = group.Description; sg.Properties.VpcId = group.VpcId; foreach (IpPermission perms in group.IpPermissions) { for (int i = 0; i < perms.IpRanges.Count; i++) { EC2SecurityGroupIngress sgi = new EC2SecurityGroupIngress(); //FormatProtocol - Protocol could be a number or text (e.g. 6 or tcp) sgi.IpProtocol = FormatProtocol(perms.IpProtocol); //-------------------------------------------------------------------- //FormatPortRange - Port range could be 0-0 -1-1 0-65535 string from = ""; string to = ""; FormatPortRange(perms.FromPort.ToString(), perms.ToPort.ToString(), out from, out to); sgi.FromPort = from; sgi.ToPort = to; //------------------------------------------------------ sgi.CidrIp = perms.IpRanges[i]; sg.Properties.SecurityGroupIngress.Add(sgi); if (log) { Utils.WriteToFile(logFile, " Protocol: " + perms.IpProtocol + " | From: " + perms.FromPort.ToString() + " To: " + perms.ToPort.ToString(), true); } } for (int i = 0; i < perms.UserIdGroupPairs.Count; i++) { EC2SecurityGroupIngress sgi = new EC2SecurityGroupIngress(); //FormatProtocol - Protocol could be a number or text (e.g. 6 or tcp) sgi.IpProtocol = FormatProtocol(perms.IpProtocol); //-------------------------------------------------------------------- //FormatPortRange - Port range could be 0-0 -1-1 0-65535 string from = ""; string to = ""; FormatPortRange(perms.FromPort.ToString(), perms.ToPort.ToString(), out from, out to); sgi.FromPort = from; sgi.ToPort = to; //------------------------------------------------------- sg.Properties.SecurityGroupIngress.Add(sgi); string groupName; if (secGroupMap.TryGetValue(perms.UserIdGroupPairs[i].GroupId, out groupName)) { sgi.SourceSecurityGroupId = groupName; } else { sgi.SourceSecurityGroupId = perms.UserIdGroupPairs[i].GroupId; } if (log) { Utils.WriteToFile(logFile, " Protocol: " + perms.IpProtocol + " | From: " + perms.FromPort.ToString() + " To: " + perms.ToPort.ToString(), true); } } } stack.Resources.Add(sg); } }
public EC2Connector(String myaccesskey, String mysecretkey, String region) { var awsCredentials = new BasicAWSCredentials(myaccesskey, mysecretkey); ec2Client = new AmazonEC2Client(awsCredentials, Regions.RegionEndpointFromName(region)); }
static void Main(string[] args) { // Create an EC2 Client for use in examples AmazonEC2Client ec2Client = new AmazonEC2Client(); }
public AWSEC2API(AWSEC2Options awsEC2Options) { this.awsEC2Options = awsEC2Options; basicAWSCredentials = new BasicAWSCredentials(awsEC2Options.Key, awsEC2Options.Secret); amazonEC2Client = new AmazonEC2Client(basicAWSCredentials, RegionEndpoint.GetBySystemName(awsEC2Options.Region)); }
public Function() { // Create EC2 client designated region where you can start/stop instances. client = new AmazonEC2Client(Amazon.RegionEndpoint.APNortheast1); }
/// <summary> /// Return csv file content for EBS snapshot /// </summary> /// <returns>The images as csv.</returns> /// <param name="input">Input.</param> /// <param name="context">Context.</param> private String getImagesAsCsv(EBSReportInput input, ILambdaContext context) { String accountId = context.InvokedFunctionArn.Split(':')[4]; var ec2Client = new AmazonEC2Client(); var getSnapshotsRequest = new DescribeSnapshotsRequest(); getSnapshotsRequest.MaxResults = 1000; //show only owned completed snapshots getSnapshotsRequest.Filters.Add(new Amazon.EC2.Model.Filter("status", new List <string> { "completed" })); getSnapshotsRequest.Filters.Add(new Amazon.EC2.Model.Filter("owner-id", new List <string> { accountId })); List <Snapshot> snapshots = new List <Snapshot>(); do { var taskResponse = ec2Client.DescribeSnapshotsAsync(getSnapshotsRequest); taskResponse.Wait(); snapshots.AddRange(taskResponse.Result.Snapshots); context.Logger.LogLine($"Added {taskResponse.Result.Snapshots.Count} snapshots to results list"); getSnapshotsRequest.NextToken = taskResponse.Result.NextToken; } while (getSnapshotsRequest.NextToken != null); var awsCommon = new AWSCommon(); var allAMIs = awsCommon.GetAllOwnedPrivateAMIs(context); var sb = new StringBuilder(); sb.Append("DateCreated,SnapID,Name,Description,AMIRelated,AMIExists,AMI-ID,Tags\n"); snapshots.Sort((s1, s2) => - 1 * s1.StartTime.CompareTo(s2.StartTime)); snapshots.ForEach(snapshot => { var nameTag = snapshot.Tags.Find(t => t.Key.Equals("Name")); var name = nameTag != null ? nameTag.Value : ""; var notNameTags = String.Join(" ", snapshot.Tags.FindAll(t => t.Key != "Name").Select(t => $"{t.Key}={t.Value}")); bool isAmiRelated = false; bool amiExists = false; String amiId = ""; //check if ebs snapshots is related to an AMI if (snapshot.Description != null) { var amiRegex = new Regex("Created by (.*) for ami-(.*) from (.*)").Match(snapshot.Description); isAmiRelated = amiRegex.Success; amiId = isAmiRelated ? "ami-" + amiRegex.Groups[2] : ""; amiExists = allAMIs.Find(i => i.ImageId.Equals(amiId)) != null; } //if only orphans to be reported, check if orphan (related to ami, ami does not exist) if (!input.OnlyAMIOrphans) { sb.Append($"{snapshot.StartTime},{snapshot.SnapshotId},{name},{snapshot.Description},{isAmiRelated},{amiExists},{amiId},{notNameTags}\n"); } else if (isAmiRelated && !amiExists) { sb.Append($"{snapshot.StartTime},{snapshot.SnapshotId},{name},{snapshot.Description},{isAmiRelated},{amiExists},{amiId},{notNameTags}\n"); } else if (isAmiRelated && amiExists) { context.Logger.LogLine($"Skipping snap {snapshot.SnapshotId} as AMI {amiId} exists"); } else if (!isAmiRelated) { context.Logger.LogLine($"Skipping snap {snapshot.SnapshotId} as non-ami related snapshot"); } }); return(sb.ToString()); }