如何在Bitbucket Pipe中使用仓库配置的SSH Key与Known Hosts?
Great question—this is a common gotcha when working with Bitbucket Pipes! The short answer is yes, you can leverage your repository's pre-configured SSH key and known hosts in pipes, but they don’t get inherited automatically. You’ll need to explicitly pass these values into the pipe’s environment to make SSH connections work without authentication errors.
Here’s how to set it up properly:
1. Pass the Repository SSH Key to the Pipe
Bitbucket stores your repo’s SSH key as a secure built-in variable called BITBUCKET_SSH_KEY. You can inject this into your pipe by adding it as an environment variable in your bitbucket-pipelines.yml file:
pipelines: default: - step: name: Run Pipe with SSH Access script: - pipe: your/custom-pipe:1.0.0 variables: # Pass the repo's SSH key to the pipe SSH_PRIVATE_KEY: $BITBUCKET_SSH_KEY
Inside the pipe, you’ll need to write this key to the appropriate SSH directory and set strict permissions (SSH is strict about file permissions to maintain security):
# Inside your pipe's script mkdir -p ~/.ssh echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa
2. Inject Known Hosts into the Pipe
Your repo’s pre-configured known hosts are stored in the BITBUCKET_KNOWN_HOSTS built-in variable. Pass this to the pipe using the same pattern:
variables: SSH_KNOWN_HOSTS: $BITBUCKET_KNOWN_HOSTS
Then, inside the pipe, add these hosts to the known_hosts file to avoid host verification errors:
echo "$SSH_KNOWN_HOSTS" >> ~/.ssh/known_hosts chmod 644 ~/.ssh/known_hosts
Key Notes to Avoid Headaches
- Third-party pipes: If you’re using a public pipe from the Bitbucket Pipe Registry, check its documentation first—some pipes already support accepting SSH keys/known hosts via environment variables, so you might not need to write custom logic.
- Custom pipes: If you’re building your own pipe, you can bake in logic to automatically detect and use these variables if they’re present, making it more user-friendly for other teams.
- Permissions: Never skip setting file permissions for SSH files—incorrect permissions will cause SSH to throw security errors and refuse to connect.
内容的提问来源于stack exchange,提问作者Julian

