Chef with PowerShell Scripts – Accessing Encrypted Data Bag Items

Chef data bags provide the ability to store unstructured data in JSON format. Data bags can be accessed from the chef server and can store global variables, or variables specific to an environment.
One of the great features of Chef data bags is the ability to encrypt information, such as passwords, to avoid storing sensitive data as plain text.
Data bag items can be encrypted using shared secret encryption, and then decrypted using the same secret file from a chef recipe. The items can also be decrypted with knife and used in a shell script. Here is how:

Creating passwords data bag:

mkdir data_bagspasswords
knife data bag create passwords

 
Create anmy_password.json file with the following information in passwords directory:

{
  "id": "the_password",
  "password": "[email protected]"
}

 
Create secret file using PowerShell:

$key = New-Object byte[](512)
$rng = [System.Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
[Convert]::ToBase64String($key) | Out-File " C:secretsmy_secret" -encoding "UTF8"
[array]::Clear($key, 0, $key.Length)

 
Encrypt items in data bag
To encrypt a data bag item using the secret file:

knife data bag from file passwords my_password.json --secret-file C:secretsmy_secret

 
To verify the encryption:

knife data bag show passwords the_password

The output should look like this:
ps output
 
Decrypt items in data bag with knife:

knife data bag show passwords the_password--secret-file C:secretsmy_secret

 
To get the password from the data bag and decrypt it into a variable:

$json = knife data bag show passwords the_password --secret-file C:secretsmy_secret -F json
$password = (($json -join "`n") | ConvertFrom-Json).password

 
Now you have $password variable holding the value [email protected]
Happy cooking!

Leave a Reply

Your email address will not be published. Required fields are marked *