AWS Developer 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;

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;

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.");
    string decryptedPassword = getPasswordResponse.GetDecryptedPassword(privateKey);
    Console.WriteLine("Decrypted Windows Password: {0}", decryptedPassword);

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.