Create RDS instance and send to CloudWatch/SNS
user_0649422
csharp
2 years ago
3.6 kB
4
Indexable
public async Task<string> FunctionHandler(string input, ILambdaContext context) { // Configure the AWS region and credentials var region = RegionEndpoint.USEast1; var credentials = new Amazon.Runtime.BasicAWSCredentials("yoursecretkey", "yoursecrettoken"); // Create an RDS client with the configured region and credentials var rdsClient = new AmazonRDSClient(credentials, region); // Configure the parameters for the RDS instance var dbInstanceIdentifier = "epam-rds-instance"; var dbInstanceClass = "db.t3.small"; var engine = "sqlserver-ex"; var engineVersion = "15.00.4236.7.v1"; var masterUsername = "admin"; var masterPassword = "mypassword"; var subnetGroupName = "dev-nurs-rds-subnet-group"; var allocatedStorage = 20; // Create the request to create an RDS instance var createRequest = new CreateDBInstanceRequest { DBInstanceIdentifier = dbInstanceIdentifier, DBInstanceClass = dbInstanceClass, Engine = engine, EngineVersion = engineVersion, MasterUsername = masterUsername, MasterUserPassword = masterPassword, DBSubnetGroupName = subnetGroupName, LicenseModel = "license-included", AllocatedStorage = allocatedStorage }; // Create the RDS instance var response = await rdsClient.CreateDBInstanceAsync(createRequest); // Add a CloudWatch notification var cloudWatchClient = new AmazonCloudWatchClient(credentials, region); var snsClient = new AmazonSimpleNotificationServiceClient(credentials, RegionEndpoint.USEast1); // Set up SNS topic to receive CloudWatch alarm notification CreateTopicRequest snsRequest = new CreateTopicRequest { Name = "RDSInstanceCreated", }; CreateTopicResponse snsResponse = await snsClient.CreateTopicAsync(snsRequest); // Subscribe email address to SNS topic SubscribeRequest subscribeRequest = new SubscribeRequest { TopicArn = snsResponse.TopicArn, Protocol = "email", Endpoint = "anurself@gmail.com" }; SubscribeResponse subscribeResponse = await snsClient.SubscribeAsync(subscribeRequest); var cwRequest = new PutMetricAlarmRequest { AlarmName = $"RDS Instance Created: {dbInstanceIdentifier}", ActionsEnabled = true, AlarmActions = new List<string> { snsResponse.TopicArn }, MetricName = "DatabaseConnections", Namespace = "AWS/RDS", Statistic = "Sum", ComparisonOperator = "GreaterThanOrEqualToThreshold", Threshold = 1, Period = 60, EvaluationPeriods = 1, Dimensions = new List<Dimension> { new Dimension { Name = "DBInstanceIdentifier", Value = dbInstanceIdentifier } } }; PutMetricAlarmResponse cwResponse = await cloudWatchClient.PutMetricAlarmAsync(cwRequest); // Create a new PublishRequest var publishRequest = new PublishRequest { TopicArn = snsResponse.TopicArn, Message = $"RDS Instance Created: {dbInstanceIdentifier}" }; // Publish the message to the SNS topic var publishResponse = await snsClient.PublishAsync(publishRequest); return response.DBInstance.DBInstanceStatus; }
Editor is loading...