Scott's Weblog The weblog of an IT pro focusing on cloud computing, Kubernetes, Linux, containers, and networking

Managing AWS Key Pairs with Pulumi and Go

As I was winding down things at Kong and getting ready to transition to Pulumi (more information on why I moved to Pulumi here), I casually made the comment on Twitter that I needed to start managing my AWS key pairs using Pulumi. When the opportunity arose last week, I started doing exactly that! In this post, I’ll show you a quick example of how to use Pulumi and Go to declaratively manage AWS key pairs.

This is a pretty simple example, so let’s just jump straight to the code:

_, err := ec2.NewKeyPair(ctx, "aws-rsa-keypair", &ec2.KeyPairArgs{
	KeyName:   pulumi.String("key-pair-name"),
	PublicKey: pulumi.String("<ssh-key-material-here>"),
	Tags: pulumi.StringMap{
		"Owner":   pulumi.String("User Name"),
		"Team":    pulumi.String("Team Name"),
		"Purpose": pulumi.String("Public key for authenticating to AWS EC2 instances"),
	if err != nil {
		return err

This code is, by and large, pretty self-explanatory. For PublicKey, you just need to supply the contents of the public key file (use cat or similar to get the contents of the file) where it shows <ssh-key-material-here>. Then specify an appropriate name and adjust the tags as desired. In this particular case, I’m “throwing away” the reference to the newly-created key pair (note the _, err := ec2.NewKeyPair; the underscore indicates I’m discarding that value) because I don’t need to refer to it anywhere else. If I did need to refer to it elsewhere (say, I was going to create a new key pair and launch an instance in the same Pulumi program), then I’d want to catch that return value.

For more information, the API docs for this resource are found here.

In the event you’re wondering how this snippet of code manages key pairs in multiple regions…well, that’s where stacks come into play. You can create multiple stacks for any Pulumi project (including this one), and each stack can target a specific AWS region. This is exactly the approach I’m using. For completeness’ sake, the process looks something like this:

  1. Run pulumi stack init to create a new stack. Specify the name of the new stack.
  2. Run pulumi config set aws:region <asw-region>, replacing <aws-region> with the name of the AWS region this stack should target.
  3. Run pulumi up and you’re good to go.

I hope this example is useful to someone. If you have any questions, feel free to reach out to me on Twitter or find me in the Pulumi community Slack (sign up for the Pulumi community Slack here if you don’t already have an account).

Metadata and Navigation

Be social and share this post!