PHP code example of titoshadow / ansible-vault

1. Go to this page and download the library: Download titoshadow/ansible-vault library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

titoshadow / ansible-vault example snippets


use Titoshadow\AnsibleVault\AnsibleVault;

...

// Default (uses PATH) $vault = new AnsibleVault();
// Custom binary path $vault = new AnsibleVault(binary: '/usr/local/bin/ansible-vault');
// Or via environment putenv('ANSIBLE_VAULT_BIN=/opt/ansible/ansible-vault'); $vault = new AnsibleVault();
// Create an instance of the library

$vault = new AnsibleVault('/path/to/vault-password-file');
 
use Titoshadow\AnsibleVault\CommandExecutor; 
use Titoshadow\AnsibleVault\AnsibleVault;

$executor = new CommandExecutor(defaultTimeout: 120.0, defaultCwd: '/srv/project');
$vault = new AnsibleVault(executor: $executor);

// stdin-name defaults to "secret" 
$encrypted = $vault->encryptString('Sensitive data', password: 'vault_pwd');
// Custom name to make output variable-friendly 
$encrypted = $vault->encryptString('Sensitive data', password: 'vault_pwd', stdinName: 'my_secret');
 
$decryptedString = $vault->decryptString($encrypted, password: 'vault_pwd');
 
vault->encrypt('/path/plain.txt', password: 'vault_pwd');
// or with an existing password
filevault->encrypt('/path/plain.txt', vaultPasswordFile: '/path/vault.pass');
 
$vault->decrypt('/path/secret.txt', password: 'vault_pwd')
 
$vault->create('/path/vault.yml', password: 'vault_pwd', encrypted: true);
 
$vault->edit('/path/vault.yml', password: 'vault_pwd'); 
 
$vault->rekey('/path/vault.yml', oldPassword: 'old', newPassword: 'new')
 
$vault->remove('/path/vault.yml');

use Titoshadow\AnsibleVault\CommandExecutor; 
use Titoshadow\AnsibleVault\Encrypter;
$encrypter = new Encrypter(new CommandExecutor());
$encrypted = encrypter->encryptSshPasswordVar('ssh_password', password: 'vault_pwd'); 
//encrypted starts with "$ANSIBLE_VAULT;"
 
use Titoshadow\AnsibleVault\Exception\VaultAuthException; 
use Titoshadow\AnsibleVault\Exception\VaultCliUsageException; 
use Titoshadow\AnsibleVault\Exception\VaultExecutionException;

try {
    $vault->decrypt('/path/secret.txt', password: 'wrong'); 
} catch (VaultAuthExceptione) {
// wrong password 
} catch (VaultCliUsageException e) {
 // invalid CLI usage 
} catch (VaultExecutionExceptione) {
// generic error (message is sanitized) 
}