We use the following testing program to start a port forwarding session by AWS SDK in C#, and the program finishes running without any issue. However, after the program finishes running, the session terminates in less than 30 seconds.
More information:
It looks like, the sessions started by the SDK do not really work. We are still looking for why.
We developed unit tests to start a session and immediately followed by a login request to connect to the database. And the result is:
If the session was started by C# calling commands of AWS CLI, the test passes.
If the session was started by C# calling APIs in SDK, the test fails with the following error message:
MySQL login failed.
ex.Message: Unable to connect to any of the specified MySQL hosts.
If we use AWS CLI instead of SDK, the following command can start a session and persist. The command will keep running and the session keeps working and accepting requests. Until we press Control + C, the process gets killed and the session terminates.
Therefore, we believe our credentials do not have any issue.
aws ssm start-session \
--target "i-xxx" --region "xxxxxxx" --profile "profile_name" \
--document-name "AWS-StartPortForwardingSessionToRemoteHost" \
--parameters host="xxxx-database-cluster.xxx.rds.amazonaws",portNumber="3306",localPortNumber="3306"
We prefer to use SDK because it provides better functionality for programmatical usage, so please point out if we missed anything in the program.
Details
Note: The following testing source code automatically refers to the default location in ~/.aws/
for its config
and credentials
files.
public static async Task CallSDKAsync()
{
// Load AWS credentials from the specified profile
var credentials = new Amazon.Runtime.StoredProfileAWSCredentials(SensitiveData.AwsProfile);
// Create the SSM client using the credentials
var client = new AmazonSimpleSystemsManagementClient(credentials, SensitiveData.AwsRegionEndpoint);
// Define the port forwarding parameters
var startSessionRequest = new StartSessionRequest
{
DocumentName = "AWS-StartPortForwardingSessionToRemoteHost",
Parameters = new Dictionary<string, List<string>>()
{
{ "host", new List<string> { SensitiveData.DatabaseHost } },
{ "portNumber", new List<string> { "3306" } },
{ "localPortNumber", new List<string> { "3306" } }
},
Target = SensitiveData.AwsInstanceId
};
try
{
var response = await client.StartSessionAsync(startSessionRequest);
Console.WriteLine(response.ToString());
Console.WriteLine("Session started successfully.");
}
catch (AmazonServiceException amazonEx)
{
Console.WriteLine($"AWS Service error: {amazonEx.Message}");
Console.WriteLine($"Status Code: {amazonEx.StatusCode}");
Console.WriteLine($"AWS Error Code: {amazonEx.ErrorCode}");
Console.WriteLine($"Request ID: {amazonEx.RequestId}");
Console.WriteLine($"AWS Error Type: {amazonEx.ErrorType}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
Console.WriteLine(ex.InnerException?.Message);
}
}