Merge pull request #133 from benben/master
[puppet-modules/puppetlabs-apt.git] / manifests / key.pp
1 define apt::key (
2   $key = $title,
3   $ensure = present,
4   $key_content = false,
5   $key_source = false,
6   $key_server = 'keyserver.ubuntu.com'
7 ) {
8
9   include apt::params
10
11   $upkey = upcase($key)
12   # trim the key to the last 8 chars so we can match longer keys with apt-key list too
13   $trimmedkey = regsubst($upkey, '^.*(.{8})$', '\1')
14
15   if $key_content {
16     $method = 'content'
17   } elsif $key_source {
18     $method = 'source'
19   } elsif $key_server {
20     $method = 'server'
21   }
22
23   # This is a hash of the parts of the key definition that we care about.
24   # It is used as a unique identifier for this instance of apt::key. It gets
25   # hashed to ensure that the resource name doesn't end up being pages and
26   # pages (e.g. in the situation where key_content is specified).
27   $digest = sha1("${upkey}/${key_content}/${key_source}/${key_server}/")
28
29   # Allow multiple ensure => present for the same key to account for many
30   # apt::source resources that all reference the same key.
31   case $ensure {
32     present: {
33
34       anchor { "apt::key/${title}": }
35
36       if defined(Exec["apt::key ${upkey} absent"]) {
37         fail("Cannot ensure Apt::Key[${upkey}] present; ${upkey} already ensured absent")
38       }
39
40       if !defined(Anchor["apt::key ${upkey} present"]) {
41         anchor { "apt::key ${upkey} present": }
42       }
43
44       if !defined(Exec[$digest]) {
45         $digest_command = $method ? {
46           'content' => "echo '${key_content}' | /usr/bin/apt-key add -",
47           'source'  => "wget -q '${key_source}' -O- | apt-key add -",
48           'server'  => "apt-key adv --keyserver '${key_server}' --recv-keys '${upkey}'",
49         }
50         exec { $digest:
51           command   => $digest_command,
52           path      => '/bin:/usr/bin',
53           unless    => "/usr/bin/apt-key list | /bin/grep '${trimmedkey}'",
54           logoutput => 'on_failure',
55           before    => Anchor["apt::key ${upkey} present"],
56         }
57       }
58
59       Anchor["apt::key ${upkey} present"] -> Anchor["apt::key/${title}"]
60
61     }
62     absent: {
63
64       if defined(Anchor["apt::key ${upkey} present"]) {
65         fail("Cannot ensure Apt::Key[${upkey}] absent; ${upkey} already ensured present")
66       }
67
68       exec { "apt::key ${upkey} absent":
69         command   => "apt-key del '${upkey}'",
70         path      => '/bin:/usr/bin',
71         onlyif    => "apt-key list | grep '${trimmedkey}'",
72         user      => 'root',
73         group     => 'root',
74         logoutput => 'on_failure',
75       }
76     }
77
78     default: {
79       fail "Invalid 'ensure' value '${ensure}' for aptkey"
80     }
81   }
82 }