AWS Developer Tools Blog

Getting your Amazon EC2 Windows Password with the AWS SDK for .NET

When you launch a Windows instance in EC2, a password will be generated for the Windows administrator user. You can retrieve this administrator’s password by using the AWS SDK for .NET.

In order to be able get the administrator password, you need to launch the EC2 instance with a key pair. To create a key pair, call the CreateKeyPair method.

string keyPairName = "get-my-password";
var createKeyPairResponse = ec2Client.CreateKeyPair(new CreateKeyPairRequest()
{
    KeyName = keyPairName
});

// The private key for the key pair used to decrypt the password.
string privateKey = createKeyPairResponse.KeyPair.KeyMaterial;
C#

It is important when creating a key pair to save the private key. This is required to be able to decrypt the password.

Now, when launching the EC2 instance, you need to set the key pair.

// Use the ImageUtilities from the Amazon.EC2.Util namespace to look up the latest Windows 2012 AMI
var image = ImageUtilities.FindImage(ec2Client, ImageUtilities.WINDOWS_2012_BASE);
var runInstanceResponse = ec2Client.RunInstances(new RunInstancesRequest()
{
    ImageId = image.ImageId,
    KeyName = keyPairName,
    InstanceType = InstanceType.T1Micro,
    MaxCount = 1,
    MinCount = 1
});

// Capture the instance ID
string instanceId = runInstanceResponse.Reservation.Instances[0].InstanceId;
C#

Once you’ve launched the instance, it will take a few minutes for the password to become available. To get the password, call the GetPasswordData method. If the PasswordData property on the response from GetPasswordData is null, then the password is not available yet.

var getPasswordResponse = ec2Client.GetPasswordData(new GetPasswordDataRequest()
{
    InstanceId = instanceId
});

if (string.IsNullOrEmpty(getPasswordResponse.PasswordData))
{
    Console.WriteLine("Password not available yet.");
}
else
{
    string decryptedPassword = getPasswordResponse.GetDecryptedPassword(privateKey);
    Console.WriteLine("Decrypted Windows Password: {0}", decryptedPassword);
}
C#

If the PasswordData property is not null, then it contains the encrypted administrator password. The utility method GetDecryptedPassword on GetPasswordReponse takes in the private key from the key pair and decrypts the password.

TAGS:
Norm Johanson

Norm Johanson

Norm Johanson has been a software developer for more than 20 years developing all types of applications. Since 2010 he has been working for AWS focusing on the .NET developer experience at AWS. His experience goes back to .NET Framework 1.0 and has been his main development platform since. These days Norm is focused on combining the power of AWS and .NET Core to help .NET developers modernize their applications. You can find Norm on Twitter at @socketnorm