Class: Chef::Knife::Annex

Inherits:
Chef::Knife show all
Defined in:
lib/chef/knife/annex.rb

Constant Summary collapse

DATA_BAG =
'annex'
IGNORE_USERS =
['admin']

Instance Method Summary collapse

Instance Method Details

#adminsObject



20
21
22
23
24
25
# File 'lib/chef/knife/annex.rb', line 20

def admins
  @admins ||= Chef::User.list.
    keys.
    select { |u| !IGNORE_USERS.include?(u) && Chef::User.load(u).admin }.
    join(',')
end

#annex_fileObject



31
32
33
# File 'lib/chef/knife/annex.rb', line 31

def annex_file
  ENV['ANNEX_FILE']
end

#annex_keyObject



27
28
29
# File 'lib/chef/knife/annex.rb', line 27

def annex_key
  ENV['ANNEX_KEY']
end

#item_idObject



35
36
37
38
39
40
# File 'lib/chef/knife/annex.rb', line 35

def item_id
  # We substitute characters invalid for data bag item id with
  # underscore, and add "__i" to allow any file extension
  # including ".keys" without confusing list for rekey.
  @item_id ||= annex_key.gsub(/[^[:alnum:]_\-]+/, '_') << "__i"
end

#runObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/chef/knife/annex.rb', line 42

def run
  case ENV['ANNEX_ACTION']
  when 'store'
    begin
      item = ChefVault::Item.load(DATA_BAG, item_id)
    rescue ChefVault::Exceptions::KeysNotFound,
           ChefVault::Exceptions::ItemNotFound
      item = ChefVault::Item.new(DATA_BAG, item_id)
    end
    item['data'] = File.read(annex_file)
    item.admins(admins)
    item.save
  when 'retrieve'
    item = ChefVault::Item.load(DATA_BAG, item_id)
    if annex_file
      File.write(annex_file, item['data'])
    else
      puts item['data']
    end
  when 'remove'
    delete_object(ChefVault::Item, "#{DATA_BAG}/#{item_id}", "chef_vault_item") do
      ChefVault::Item.load(DATA_BAG, item_id).destroy
    end
  when 'checkpresent'
    begin
      ChefVault::Item.load(DATA_BAG, item_id)
    rescue ChefVault::Exceptions::KeysNotFound,
           ChefVault::Exceptions::ItemNotFound
      # not found, we do nothing
    else
      # found, print original key
      puts annex_key
    end
  else
    item_ids = ( @name_args.empty? ?
      Chef::DataBag.load(DATA_BAG).keys.grep(/__i$/) :
      @name_args )
    if config[:rotate_keys]
      item_ids.each do |item_id|
        item = ChefVault::Item.load(DATA_BAG, item_id)
        item.admins(item.admins.join(','), :delete)
        item.admins(admins)
        item.rotate_keys!
      end
    else
      puts "Use this command as git-annex hook"
    end
  end
end