Skip to content

Instantly share code, notes, and snippets.

@navarr
Created June 6, 2016 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navarr/35aa1965c040831fc37e32f2d771d0d4 to your computer and use it in GitHub Desktop.
Save navarr/35aa1965c040831fc37e32f2d771d0d4 to your computer and use it in GitHub Desktop.
Properly format a string into a Private Key
#!/usr/local/bin/php
<?php
// Does the environment variable exist?
if (!isset($_ENV['ID_RSA'])) {
error_log("ID_RSA Environment Variable not set");
return;
}
$id_rsa = $_ENV['ID_RSA'];
$file = '/root/.ssh/id_rsa';
// Create folder if does not exist
if (!file_exists(dirname($file))) {
mkdir(dirname($file));
}
$header = '-----BEGIN RSA PRIVATE KEY-----';
$footer = '-----END RSA PRIVATE KEY-----';
$lines = str_split($id_rsa, 64);
$text = '';
$text .= $header.PHP_EOL;
array_walk($lines, function ($line) use (&$text) {
$text .= $line.PHP_EOL;
});
$text .= $footer.PHP_EOL;
file_put_contents($file, $text);
chmod($file, 0600);
@navarr
Copy link
Author

navarr commented Jun 6, 2016

This particular script was written for turning a Bitbucket Pipeline environment variable (ID_RSA) into a Private Key file for ssh private key authentication deployments.

Since Pipeline environment variables do not allow newlines, this was necessary in order to create a private key file on a docker image without building it into the docker image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment