How to provide a condition within Chef recipe to s

2019-07-27 10:43发布

问题:

I am using encrypted data bags within Chef and I want to add a condition within my Chef recipe as follows:

If (test kitchen) then
  encryptkey = data_bag_item("tokens", "encryptkey")

If ( not test kitchen ) then
  secret = Chef::EncryptedDataBagItem.load_secret("/etc/chef/encrypted_data_bag_secret")
  encryptkey = Chef::EncryptedDataBagItem.load("tokens", "encryptkey", secret)

I have added data_bags_path and encrypted_data_bag_secret_key_path within kitchen.yml as follows:

provisioner:
  name: chef_zero
  chef_omnibus_url: omni-url/chef/install.sh
  roles_path: 'test/integration/default/roles'
  data_bags_path: "test/integration/default/data_bags"
  encrypted_data_bag_secret_key_path: "test/integration/default/encrypted_data_bag_secret"

回答1:

Use the attributes in your kitchen.yaml.

  suites:
  - name: default
    data_bags_path: 'databags'
    run_list:
      - recipe[x::y]
    attributes: {'kitchen' : 'true' }

Inside your recipe put if condition using the value of node['chef-mode'].

if node['kitchen'] == 'true'
    #something
else
   #else 
end


回答2:

Just use data_bag_item("tokens", "encryptkey") for both. It will take care of decryption for you automatically.