Working with Ansible vaults in Go

Vault is a feature of Ansible that allows keeping sensitive data such as passwords or keys in encrypted files, rather than as plaintext in your playbooks or roles. These vault files can then be distributed or placed in source control. Vault is also just a fancy name for files (or strings) with encrypted and formatted content.

Vault secret data typically looks like this:

$ANSIBLE_VAULT;1.1;AES256
63623566326538326634613931303733326439646130316566653930616264656431626135303933
6266626261373039363436353766613666356331653866310a303637623931666464326234616334
34303333663837316437613531383566633065333563616437356337643965336131376266366431
3031303331323232650a373739393962343137316261383931383436633262303661303537326462
3732

Vault files are generated (or modified) with ansible-vault command which is a Python-based CLI tool that ships with Ansible. All secret data is protected by a user-generated password that should never be checked into any source code repository. These secrets are then consumed by Ansible playbooks or by any third-party module.

Reading and writing AES256 vault files is pretty straightforward and there are libraries for other languages like Ruby. After using a small Go script that deals with vault files i finally decided to make an open source package that i can reuse across projects instead of copy pasting it every time.

Package is available on Github: ansible-vault-go

Installation

To install run the command:

go get -u github.com/sosedoff/ansible-vault-go

Documentation is hosted on GoDoc

Examples

package main

import(
  "log"

  "github.com/sosedoff/ansible-vault-go"
)

func main() {
  // Encrypt secret data
  str, err := vault.Encrypt("secret", "password")

  // Decrypt secret data
  str, err := vault.Decrypt("secret", "password")

  // Write secret data to file
  err := vault.EncryptFile("path/to/secret/file", "secret", "password")

  // Read existing secret
  str, err := vault.DecryptFile("path/to/secret/file", "password")
}