How do I associate key pairs with auto-scaling groups on AWS?
In this guide, we will demonstrate how to create an EC2 Key Pair and associate it with an Auto-Scaling Group on AWS using Pulumi. This setup ensures that instances launched by the Auto-Scaling Group can be accessed using the specified key pair.
Key Points:
- Create an EC2 Key Pair.
- Define a Launch Configuration using the Key Pair.
- Create an Auto-Scaling Group with the Launch Configuration.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an EC2 Key Pair
const keyPair = new aws.ec2.KeyPair("myKeyPair", {
keyName: "my-key-pair",
publicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA7..." // Replace with your actual public key
});
// Create a Launch Configuration using the Key Pair
const launchConfiguration = new aws.ec2.LaunchConfiguration("myLaunchConfig", {
imageId: "ami-0c55b159cbfafe1f0", // Replace with a valid AMI ID
instanceType: "t2.micro",
keyName: keyPair.keyName,
securityGroups: ["sg-0a1234567890abcdef"], // Replace with your security group ID
userData: `#!/bin/bash
echo "Hello, World!" > index.html
nohup python -m SimpleHTTPServer 80 &`
});
// Create an Auto-Scaling Group with the Launch Configuration
const autoScalingGroup = new aws.autoscaling.Group("myAutoScalingGroup", {
launchConfiguration: launchConfiguration.id,
minSize: 1,
maxSize: 3,
desiredCapacity: 2,
vpcZoneIdentifiers: ["subnet-0bb1c79de3EXAMPLE"], // Replace with your subnet ID
tags: [{
key: "Name",
value: "my-auto-scaling-group",
propagateAtLaunch: true,
}],
});
// Export the name of the Key Pair and Auto-Scaling Group
export const keyPairName = keyPair.keyName;
export const autoScalingGroupName = autoScalingGroup.name;
Summary
In this guide, we created an EC2 Key Pair and associated it with an Auto-Scaling Group on AWS. We defined a Launch Configuration that uses the Key Pair and created an Auto-Scaling Group with this Launch Configuration. This setup allows us to securely access instances launched by the Auto-Scaling Group using the specified Key Pair.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.