How do I configure SSH private keys for Ansible dynamic inventory in Spacelift?

Last updated: December 19, 2025

Context

When setting up an Ansible stack in Spacelift with dynamic inventory for EC2 instances, you need to properly configure SSH private keys to enable connection to your instances. This requires specific setup of the private key file and appropriate permissions.

Answer

To configure SSH private keys for Ansible dynamic inventory in Spacelift, follow these steps:

  1. Add your SSH private key as a mounted secret file in Spacelift

  2. Set an environment variable named ANSIBLE_PRIVATE_KEY_FILE pointing to the mounted secret location: /mnt/secrets/ec2.pem

  3. Add a before init hook to set the correct file permissions using the following command: chmod 600 /path/to/your/mounted/key. You may need to also add this to a before plan hook as when a run resumes after being paused (for example, for confirmation or approval), the remaining phases run in a new container. Any files or tools from earlier phases will not be available in the new container.

Sources: