Skip to content

Commit 93485bf

Browse files
committed
Updates for EC2.
1 parent d6ed4a6 commit 93485bf

File tree

5 files changed

+20
-232
lines changed

5 files changed

+20
-232
lines changed

dotnetv4/EC2/Actions/EC2Wrapper.cs

Lines changed: 17 additions & 181 deletions
Original file line numberDiff line numberDiff line change
@@ -288,34 +288,6 @@ public async Task<string> CreateSecurityGroup(string groupName, string groupDesc
288288

289289
// snippet-end:[EC2.dotnetv4.CreateSecurityGroup]
290290

291-
// snippet-start:[EC2.dotnetv4.CreateVPC]
292-
/// <summary>
293-
/// Create a new Amazon EC2 VPC.
294-
/// </summary>
295-
/// <param name="cidrBlock">The CIDR block for the new security group.</param>
296-
/// <returns>The VPC Id of the new VPC.</returns>
297-
public async Task<string?> CreateVPC(string cidrBlock)
298-
{
299-
300-
try
301-
{
302-
var response = await _amazonEC2.CreateVpcAsync(new CreateVpcRequest
303-
{
304-
CidrBlock = cidrBlock,
305-
});
306-
307-
Vpc vpc = response.Vpc;
308-
Console.WriteLine($"Created VPC with ID: {vpc.VpcId}.");
309-
return vpc.VpcId;
310-
}
311-
catch (AmazonEC2Exception ex)
312-
{
313-
Console.WriteLine($"Couldn't create VPC because: {ex.Message}");
314-
return null;
315-
}
316-
}
317-
// snippet-end:[EC2.dotnetv4.CreateVPC]
318-
319291
// snippet-start:[EC2.dotnetv4.DeleteKeyPair]
320292
/// <summary>
321293
/// Delete an Amazon EC2 key pair.
@@ -391,24 +363,6 @@ await _amazonEC2.DeleteSecurityGroupAsync(
391363
}
392364
// snippet-end:[EC2.dotnetv4.DeleteSecurityGroup]
393365

394-
// snippet-start:[EC2.dotnetv4.DeleteVPC]
395-
/// <summary>
396-
/// Delete an Amazon EC2 VPC.
397-
/// </summary>
398-
/// <returns>A Boolean value indicating the success of the action.</returns>
399-
public async Task<bool> DeleteVpc(string vpcId)
400-
{
401-
var request = new DeleteVpcRequest
402-
{
403-
VpcId = vpcId,
404-
};
405-
406-
var response = await _amazonEC2.DeleteVpcAsync(request);
407-
408-
return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
409-
}
410-
// snippet-end:[EC2.dotnetv4.DeleteVPC]
411-
412366
// snippet-start:[EC2.dotnetv4.DescribeImages]
413367
/// <summary>
414368
/// Get information about existing Amazon EC2 images.
@@ -428,20 +382,6 @@ public async Task<List<Image>> DescribeImages(List<string>? imageIds)
428382
return response.Images;
429383
}
430384

431-
/// <summary>
432-
/// Display the information returned by DescribeImages.
433-
/// </summary>
434-
/// <param name="images">The list of image information to display.</param>
435-
public void DisplayImageInfo(List<Image> images)
436-
{
437-
images.ForEach(image =>
438-
{
439-
Console.WriteLine($"{image.Name} Created on: {image.CreationDate}");
440-
});
441-
442-
}
443-
// snippet-end:[EC2.dotnetv4.DescribeImages]
444-
445385
// snippet-start:[EC2.dotnetv4.DescribeInstance]
446386
/// <summary>
447387
/// Get information about an Amazon EC2 instance.
@@ -471,62 +411,6 @@ public void DisplayInstanceInformation(Instance instance)
471411
}
472412
// snippet-end:[EC2.dotnetv4.DescribeInstance]
473413

474-
// snippet-start:[EC2.dotnetv4.DescribeInstances]
475-
/// <summary>
476-
/// Get information about EC2 instances with a particular state.
477-
/// </summary>
478-
/// <param name="tagName">The name of the tag to filter on.</param>
479-
/// <param name="tagValue">The value of the tag to look for.</param>
480-
/// <returns>True if successful.</returns>
481-
public async Task<bool> GetInstancesWithState(string state)
482-
{
483-
try
484-
{
485-
// Filters the results of the instance list.
486-
var filters = new List<Filter>
487-
{
488-
new Filter
489-
{
490-
Name = $"instance-state-name",
491-
Values = new List<string> { state, },
492-
},
493-
};
494-
var request = new DescribeInstancesRequest { Filters = filters, };
495-
496-
Console.WriteLine($"\nShowing instances with state {state}");
497-
var paginator = _amazonEC2.Paginators.DescribeInstances(request);
498-
499-
await foreach (var response in paginator.Responses)
500-
{
501-
foreach (var reservation in response.Reservations)
502-
{
503-
foreach (var instance in reservation.Instances)
504-
{
505-
Console.Write($"Instance ID: {instance.InstanceId} ");
506-
Console.WriteLine($"\tCurrent State: {instance.State.Name}");
507-
}
508-
}
509-
}
510-
511-
return true;
512-
}
513-
catch (AmazonEC2Exception ec2Exception)
514-
{
515-
if (ec2Exception.ErrorCode == "InvalidParameterValue")
516-
{
517-
_logger.LogError(
518-
$"Invalid parameter value for filtering instances.");
519-
}
520-
521-
return false;
522-
}
523-
catch (Exception ex)
524-
{
525-
Console.WriteLine($"Couldn't list instances because: {ex.Message}");
526-
return false;
527-
}
528-
}
529-
// snippet-end:[EC2.dotnetv4.DescribeInstances]
530414

531415
// snippet-start:[EC2.dotnetv4.DescribeInstanceTypes]
532416
/// <summary>
@@ -585,6 +469,7 @@ public async Task<List<KeyPairInfo>> DescribeKeyPairs(string keyPairName)
585469
{
586470
try
587471
{
472+
var pairs = new List<KeyPairInfo>();
588473
var request = new DescribeKeyPairsRequest();
589474
if (!string.IsNullOrEmpty(keyPairName))
590475
{
@@ -595,7 +480,12 @@ public async Task<List<KeyPairInfo>> DescribeKeyPairs(string keyPairName)
595480
}
596481

597482
var response = await _amazonEC2.DescribeKeyPairsAsync(request);
598-
return response.KeyPairs.ToList();
483+
if (response.KeyPairs != null)
484+
{
485+
pairs = response.KeyPairs.ToList();
486+
}
487+
return pairs;
488+
599489
}
600490
catch (AmazonEC2Exception ec2Exception)
601491
{
@@ -674,36 +564,36 @@ public void DisplaySecurityGroupInfoAsync(SecurityGroup securityGroup)
674564
{
675565
Console.WriteLine($"{securityGroup.GroupName}");
676566
Console.WriteLine("Ingress permissions:");
677-
securityGroup.IpPermissions.ForEach(permission =>
567+
securityGroup.IpPermissions?.ForEach(permission =>
678568
{
679569
Console.WriteLine($"\tFromPort: {permission.FromPort}");
680570
Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");
681571

682572
Console.Write($"\tIpv4Ranges: ");
683-
permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });
573+
permission.Ipv4Ranges?.ForEach(range => { Console.Write($"{range.CidrIp} "); });
684574

685575
Console.WriteLine($"\n\tIpv6Ranges:");
686-
permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });
576+
permission.Ipv6Ranges?.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });
687577

688578
Console.Write($"\n\tPrefixListIds: ");
689-
permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));
579+
permission.PrefixListIds?.ForEach(id => Console.Write($"{id.Id} "));
690580

691581
Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
692582
});
693583
Console.WriteLine("Egress permissions:");
694-
securityGroup.IpPermissionsEgress.ForEach(permission =>
584+
securityGroup.IpPermissionsEgress?.ForEach(permission =>
695585
{
696586
Console.WriteLine($"\tFromPort: {permission.FromPort}");
697587
Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");
698588

699589
Console.Write($"\tIpv4Ranges: ");
700-
permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });
590+
permission.Ipv4Ranges?.ForEach(range => { Console.Write($"{range.CidrIp} "); });
701591

702592
Console.WriteLine($"\n\tIpv6Ranges:");
703-
permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });
593+
permission.Ipv6Ranges?.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });
704594

705595
Console.Write($"\n\tPrefixListIds: ");
706-
permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));
596+
permission.PrefixListIds?.ForEach(id => Console.Write($"{id.Id} "));
707597

708598
Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
709599
});
@@ -744,60 +634,6 @@ public async Task<bool> DisassociateIp(string associationId)
744634
}
745635
// snippet-end:[EC2.dotnetv4.DisassociateAddress]
746636

747-
// snippet-start:[EC2.dotnetv4.GetAMIList]
748-
/// <summary>
749-
/// Retrieve a list of available Amazon Linux images.
750-
/// </summary>
751-
/// <returns>A list of image information.</returns>
752-
public async Task<List<Image>> GetEC2AmiList()
753-
{
754-
var filter = new Filter { Name = "architecture", Values = new List<string> { "x86_64" } };
755-
var filters = new List<Filter> { filter };
756-
var response = await _amazonEC2.DescribeImagesAsync(new DescribeImagesRequest { Filters = filters });
757-
return response.Images;
758-
}
759-
// snippet-end:[EC2.dotnetv4.GetAMIList]
760-
761-
// snippet-start:[EC2.dotnetv4.RebootInstances]
762-
/// <summary>
763-
/// Reboot a specific EC2 instance.
764-
/// </summary>
765-
/// <param name="ec2InstanceId">The instance Id of the instance that will be rebooted.</param>
766-
/// <returns>Async Task.</returns>
767-
public async Task<bool> RebootInstances(string ec2InstanceId)
768-
{
769-
try
770-
{
771-
var request = new RebootInstancesRequest
772-
{
773-
InstanceIds = new List<string> { ec2InstanceId },
774-
};
775-
776-
await _amazonEC2.RebootInstancesAsync(request);
777-
778-
// Wait for the instance to be running.
779-
Console.Write("Waiting for the instance to start.");
780-
await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);
781-
782-
return true;
783-
}
784-
catch (AmazonEC2Exception ec2Exception)
785-
{
786-
if (ec2Exception.ErrorCode == "InvalidInstanceId")
787-
{
788-
_logger.LogError(
789-
$"InstanceId {ec2InstanceId} is invalid, unable to reboot. {ec2Exception.Message}");
790-
}
791-
return false;
792-
}
793-
catch (Exception ex)
794-
{
795-
_logger.LogError(
796-
$"An error occurred while rebooting the instance {ec2InstanceId}.: {ex.Message}");
797-
return false;
798-
}
799-
}
800-
// snippet-end:[EC2.dotnetv4.RebootInstances]
801637

802638
// snippet-start:[EC2.dotnetv4.ReleaseAddress]
803639
/// <summary>
@@ -812,8 +648,8 @@ public async Task<bool> ReleaseAddress(string allocationId)
812648
{
813649
var request = new ReleaseAddressRequest { AllocationId = allocationId };
814650

815-
var response = await _amazonEC2.ReleaseAddressAsync(request);
816-
return response.HttpStatusCode == HttpStatusCode.OK;
651+
await _amazonEC2.ReleaseAddressAsync(request);
652+
return true;
817653
}
818654
catch (AmazonEC2Exception ec2Exception)
819655
{

dotnetv4/EC2/Actions/HelloEC2.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ static async Task Main(string[] args)
2828
try
2929
{
3030
// Retrieve information for up to 10 Amazon EC2 security groups.
31-
var request = new DescribeSecurityGroupsRequest { MaxResults = 10, };
31+
var request = new DescribeSecurityGroupsRequest { MaxResults = 10 };
3232
var securityGroups = new List<SecurityGroup>();
3333

3434
var paginatorForSecurityGroups =

dotnetv4/EC2/EC2Examples.sln

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basics", "Scenarios\EC2_Bas
1212
EndProject
1313
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EC2Tests", "Tests\EC2Tests.csproj", "{6046A2FC-6A39-4C2D-8DD9-AA3740B17B88}"
1414
EndProject
15-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CreateVPCExample", "Scenarios\CreateVPCExample\CreateVPCExample.csproj", "{A0B25DB2-E0BE-409F-950D-19E23FB76319}"
16-
EndProject
17-
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CreateVPCforS3Example", "Scenarios\CreateVPCforS3Example\CreateVPCforS3Example.csproj", "{CB5A94D4-1BA1-41CE-B5AE-7CE906B4CA7D}"
18-
EndProject
1915
Global
2016
GlobalSection(SolutionConfigurationPlatforms) = preSolution
2117
Debug|Any CPU = Debug|Any CPU
@@ -34,14 +30,6 @@ Global
3430
{6046A2FC-6A39-4C2D-8DD9-AA3740B17B88}.Debug|Any CPU.Build.0 = Debug|Any CPU
3531
{6046A2FC-6A39-4C2D-8DD9-AA3740B17B88}.Release|Any CPU.ActiveCfg = Release|Any CPU
3632
{6046A2FC-6A39-4C2D-8DD9-AA3740B17B88}.Release|Any CPU.Build.0 = Release|Any CPU
37-
{A0B25DB2-E0BE-409F-950D-19E23FB76319}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
38-
{A0B25DB2-E0BE-409F-950D-19E23FB76319}.Debug|Any CPU.Build.0 = Debug|Any CPU
39-
{A0B25DB2-E0BE-409F-950D-19E23FB76319}.Release|Any CPU.ActiveCfg = Release|Any CPU
40-
{A0B25DB2-E0BE-409F-950D-19E23FB76319}.Release|Any CPU.Build.0 = Release|Any CPU
41-
{CB5A94D4-1BA1-41CE-B5AE-7CE906B4CA7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
42-
{CB5A94D4-1BA1-41CE-B5AE-7CE906B4CA7D}.Debug|Any CPU.Build.0 = Debug|Any CPU
43-
{CB5A94D4-1BA1-41CE-B5AE-7CE906B4CA7D}.Release|Any CPU.ActiveCfg = Release|Any CPU
44-
{CB5A94D4-1BA1-41CE-B5AE-7CE906B4CA7D}.Release|Any CPU.Build.0 = Release|Any CPU
4533
EndGlobalSection
4634
GlobalSection(SolutionProperties) = preSolution
4735
HideSolutionNode = FALSE

dotnetv4/EC2/README.md

Lines changed: 2 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -49,36 +49,20 @@ Code excerpts that show you how to call individual service functions.
4949
- [AssociateAddress](Actions/EC2Wrapper.cs#L64)
5050
- [AuthorizeSecurityGroupIngress](Actions/EC2Wrapper.cs#L107)
5151
- [CreateKeyPair](Actions/EC2Wrapper.cs#L170)
52-
- [CreateLaunchTemplate](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L263)
5352
- [CreateSecurityGroup](Actions/EC2Wrapper.cs#L242)
5453
- [DeleteKeyPair](Actions/EC2Wrapper.cs#L319)
55-
- [DeleteLaunchTemplate](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L470)
5654
- [DeleteSecurityGroup](Actions/EC2Wrapper.cs#L361)
57-
- [DescribeAvailabilityZones](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L325)
58-
- [DescribeIamInstanceProfileAssociations](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L574)
5955
- [DescribeInstanceTypes](Actions/EC2Wrapper.cs#L531)
6056
- [DescribeInstances](Actions/EC2Wrapper.cs#L474)
6157
- [DescribeKeyPairs](Actions/EC2Wrapper.cs#L578)
6258
- [DescribeSecurityGroups](Actions/EC2Wrapper.cs#L620)
63-
- [DescribeSubnets](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L422)
64-
- [DescribeVpcs](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L386)
6559
- [DisassociateAddress](Actions/EC2Wrapper.cs#L714)
66-
- [RebootInstances](Actions/EC2Wrapper.cs#L761)
6760
- [ReleaseAddress](Actions/EC2Wrapper.cs#L802)
68-
- [ReplaceIamInstanceProfileAssociation](../cross-service/ResilientService/AutoScalerActions/AutoScalerWrapper.cs#L611)
6961
- [RunInstances](Actions/EC2Wrapper.cs#L837)
7062
- [StartInstances](Actions/EC2Wrapper.cs#L890)
7163
- [StopInstances](Actions/EC2Wrapper.cs#L930)
7264
- [TerminateInstances](Actions/EC2Wrapper.cs#L971)
7365

74-
### Scenarios
75-
76-
Code examples that show you how to accomplish a specific task by calling multiple
77-
functions within the same service.
78-
79-
- [Build and manage a resilient service](../cross-service/ResilientService/ResilientServiceWorkflow/ResilientServiceWorkflow.cs)
80-
81-
8266
<!--custom.examples.start-->
8367
<!--custom.examples.end-->
8468

@@ -87,7 +71,7 @@ functions within the same service.
8771
### Instructions
8872

8973
For general instructions to run the examples, see the
90-
[README](../README.md#building-and-running-the-code-examples) in the `dotnetv3` folder.
74+
[README](../README.md#building-and-running-the-code-examples) in the `dotnetv4` folder.
9175

9276
Some projects might include a settings.json file. Before compiling the project,
9377
you can change these values to match your own account and resources. Alternatively,
@@ -129,32 +113,13 @@ This example shows you how to do the following:
129113
<!--custom.basics.ec2_Scenario_GetStartedInstances.start-->
130114
<!--custom.basics.ec2_Scenario_GetStartedInstances.end-->
131115

132-
133-
#### Build and manage a resilient service
134-
135-
This example shows you how to create a load-balanced web service that returns book, movie, and song recommendations. The example shows how the service responds to failures, and how to restructure the service for more resilience when failures occur.
136-
137-
- Use an Amazon EC2 Auto Scaling group to create Amazon Elastic Compute Cloud (Amazon EC2) instances based on a launch template and to keep the number of instances in a specified range.
138-
- Handle and distribute HTTP requests with Elastic Load Balancing.
139-
- Monitor the health of instances in an Auto Scaling group and forward requests only to healthy instances.
140-
- Run a Python web server on each EC2 instance to handle HTTP requests. The web server responds with recommendations and health checks.
141-
- Simulate a recommendation service with an Amazon DynamoDB table.
142-
- Control web server response to requests and health checks by updating AWS Systems Manager parameters.
143-
144-
<!--custom.scenario_prereqs.cross_ResilientService.start-->
145-
<!--custom.scenario_prereqs.cross_ResilientService.end-->
146-
147-
148-
<!--custom.scenarios.cross_ResilientService.start-->
149-
<!--custom.scenarios.cross_ResilientService.end-->
150-
151116
### Tests
152117

153118
⚠ Running tests might result in charges to your AWS account.
154119

155120

156121
To find instructions for running these tests, see the [README](../README.md#Tests)
157-
in the `dotnetv3` folder.
122+
in the `dotnetv4` folder.
158123

159124

160125

0 commit comments

Comments
 (0)