public string CreateKeyPair() { string keyPairName = "Ec2Test"; KeyPairInfo myKeyPair = null; try { var dkpRequest = new DescribeKeyPairsRequest(); var dkpResponse = amazonEC2Client.DescribeKeyPairsAsync(dkpRequest).Result; List <KeyPairInfo> myKeyPairs = dkpResponse.KeyPairs; foreach (KeyPairInfo item in myKeyPairs) { Console.WriteLine("Existing key pair: " + item.KeyName); if (item.KeyName == keyPairName) { myKeyPair = item; } } if (myKeyPair == null) { var newKeyRequest = new CreateKeyPairRequest() { KeyName = keyPairName }; var ckpResponse = amazonEC2Client.CreateKeyPairAsync(newKeyRequest).Result; Console.WriteLine(); Console.WriteLine("New key: " + keyPairName); // Save the private key in a .pem file using (FileStream s = new FileStream(keyPairName + ".pem", FileMode.Create)) using (StreamWriter writer = new StreamWriter(s)) { writer.WriteLine(ckpResponse.KeyPair.KeyMaterial); } } } catch (Exception ex) { throw ex; } return(keyPairName); }
public void CreateaKeyPair() { //Create an Amazon EC2 Client Using the the SDK var ec2Client = new AmazonEC2Client(); //enumerate the key pairs string keyPairName = "my-sample-key"; KeyPairInfo myKeyPair = null; var dkpRequest = new DescribeKeyPairsRequest(); var dkpResponse = ec2Client.DescribeKeyPairs(dkpRequest); List <KeyPairInfo> myKeyPairs = dkpResponse.KeyPairs; foreach (KeyPairInfo item in myKeyPairs) { Console.WriteLine("Existing key pair: " + item.KeyName); if (item.KeyName == keyPairName) { myKeyPair = item; } } //create a key pair and save the private key if (myKeyPair == null) { var newKeyRequest = new CreateKeyPairRequest() { KeyName = keyPairName }; var ckpResponse = ec2Client.CreateKeyPair(newKeyRequest); Console.WriteLine(); Console.WriteLine("New key: " + keyPairName); // Save the private key in a .pem file using (FileStream s = new FileStream(keyPairName + ".pem", FileMode.Create)) using (StreamWriter writer = new StreamWriter(s)) { writer.WriteLine(ckpResponse.KeyPair.KeyMaterial); } } }