AWS Lambda function to return authorized keys
for EC2 SSH access.
Meant to be used with Amazon API Gateway.
Create a new IAM group and label it e.g. ssh
.
Attach the managed policy IAMUserSSHKeys
and add all users that should be
granted EC2 SSH access.
Create a new IAM role with the name
aws-lambda-ssh-authorized-keys
. Select the AWS Lambda role type and attach the
managed policy AWSLambdaBasicExecutionRole
.
Attach an additional inline policy with the following content, optionally
replacing ssh
with the IAM group created in the previous section.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iam:getGroup",
"iam:listSSHPublicKeys",
"iam:getSSHPublicKey"
],
"Resource": ["arn:aws:iam::*:group/ssh", "arn:aws:iam::*:user/*"]
}
]
}
Add the function code to AWS Lambda with the following configuration options:
Key | Value |
---|---|
Runtime | Node.js 10.x |
Handler | index.handler |
Role | aws-lambda-ssh-authorized-keys |
Memory | 128 (MB) |
Timeout | 10 sec |
Set the following optional environment variable for the Lambda function:
Key | Value |
---|---|
group | The IAM group of users authorized for SSH access, defaults to "ssh" . |
Add an API Gateway trigger with "Open" security.
No API key is necessary, as the returned keys are public by definition.
- Go to the API Gateway console.
- Navigate to the Stage Editor for the
prod
stage. - Choose
Settings
. - Select
Enable API cache
. - Set the
Cache capacity
to0.5GB
. - Set the
Cache time-to-live (TTL)
to300
(5 mins).
Use the following
EC2 user data shell script
when launching your instances, replacing ID
with the API Gateway ID of your
lambda function and REGION
with your AWS region in the curl URL:
#!/bin/sh
# Add the ssh-authorized-keys command:
# shellcheck disable=SC2016,SC1004
echo '#!/bin/sh
[ "$1" = ec2-user ] && exec curl -s \
https://ID.execute-api.REGION.amazonaws.com/prod/ssh-authorized-keys
' > /usr/local/bin/ssh-authorized-keys && chmod +x \
/usr/local/bin/ssh-authorized-keys
# Configure sshd to lookup public keys via ssh-authorized-keys command:
sed -i '/^AuthorizedKeysCommand/d' /etc/ssh/sshd_config
echo '
AuthorizedKeysCommand /usr/local/bin/ssh-authorized-keys
AuthorizedKeysCommandUser nobody
' >> /etc/ssh/sshd_config
# Check and reload the sshd config:
sshd -t && service sshd reload
Released under the MIT license.