Amazon Ec2 Instance Management with C#: Part 3 – Uploading and Importing a Key Pair

Before getting started

Skill Level: Beginner

Assumptions:

  1. You have completed Part 1 and 2 of Managing Amazon AWS with C# – EC2

Additional Information: I sometimes cover small sub-topics in a post. Along with AWS, you will also be exposed to:

  • .NET Core 2.0 – If you use .NET Framework, the steps will be slightly different, but as this is a beginner level tutorial, it should be simple.
  • Rhyous.SimpleArgs

Details

We may already have a key pair that we want to use, so we don’t want to create a new one. If that is the case, it can be uploaded.

Step 1 – Get key in the correct format

I used OpenSSL to do this.

  1. Download OpenSSL.
  2. Run this command:
    [sh]
    .\openssl.exe rsa -in c:\users\jbarneck\desktop\new.pem -pubou
    t -out c:\users\jbarneck\desktop\new.pub
    [sh]

Step 2 – Edit InstanceManager.cs file

We’ve created InstanceManager.cs in Part 1. Let’s edit it.

  1. Add a method to read the key file from disk and upload and import the key pair.
  2.         public static async Task ImportKeyPair(AmazonEC2Client ec2Client, string keyName, string keyFile)
            {
                var publicKey = File.ReadAllText(keyFile).Trim().RemoveFirstLine().RemoveLastLine();
                string publicKeyAsBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(publicKey));
                await ec2Client.ImportKeyPairAsync(new ImportKeyPairRequest(keyName, publicKeyAsBase64));
            }
    

Notice: We are calling RemoveFirstLine() and RemoveLastLine(); This is because key files have a header and footer that must be removed before sending up to AWS. We’ll do this in the next section.

Step 3 – Add methods RemoveFirstLine and RemoveLastLine

  1. By the time this publishes, you should only need to install Rhyous.String.Library. Otherwise, add this class file:
    namespace Rhyous.AmazonEc2InstanceManager
    {
        public static class StringExtensions
        {
            public static string RemoveFirstLine(this string text, char newLineChar = '\n')
            {
                if (string.IsNullOrEmpty(text))
                    return text;
                var i = text.IndexOf(newLineChar);            
                return i > 0 ? text.Substring(i + 1) : "";
            }
    
            public static string RemoveLastLine(this string text, char newLineChar = '\n')
            {
                var i = text.LastIndexOf(newLineChar);
                return (i > 0) ? text.Substring(0, i) : "";
            }
        }
    }
    

Step 4 – Configure command line Arguments.

We already have an Actions arguments to edit.

  1. Add DeleteKeyPair as a valid action to the Action argument.
  2. Add an additional argument for the key file.
                . . .
                new Argument
                {
                    Name = "Action",
                    ShortName = "a",
                    Description = "The action to run.",
                    Example = "{name}=default",
                    DefaultValue = "Default",
                    AllowedValues = new ObservableCollection<string>
                    {
                        "CreateKeyPair",
                        "DeleteKeyPair",
                        "ImportKeyPair"
                    },
                    IsRequired = true,
                    Action = (value) =>
                    {
                        Console.WriteLine(value);
                    }
                },
                . . .
                new Argument
                {
                    Name = "KeyFile",
                    ShortName = "pem",
                    Description = "The full path to a public key already created on your file system in PEM format. The full Private key won't work.",
                    Example = "{name}=c:\\My\\Path\\mykeyfile.pem",
                    CustomValidation = (value) => File.Exists(value),
                    Action = (value) =>
                    {
                        Console.WriteLine(value);
                    }
                }

You can now upload a public key file for use on the Amazon Cloud.

Next: Part 4

Return to: Managing Amazon AWS with C#

Leave a Reply

How to post code in comments?