-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathcontainer.pp
408 lines (373 loc) · 15.5 KB
/
container.pp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# @summary manage podman container and register as a systemd service
#
# @param image
# Container registry source of the image being deployed. Required when
# `ensure` is `present` but optional when `ensure` is set to `absent`.
#
# @param user
# Optional user for running rootless containers. For rootless containers,
# the user must also be defined as a puppet resource that includes at least
# 'uid', 'gid', and 'home' attributes.
#
# @param flags
# All flags for the 'podman container create' command are supported via the
# 'flags' hash parameter, using only the long form of the flag name. The
# container name will be set as the resource name (namevar) unless the 'name'
# flag is included in the flags hash. If the flags for a container resource
# are modified the container will be destroyed and re-deployed during the
# next puppet run. This is achieved by storing the complete set of flags as
# a base64 encoded string in a container label named `puppet_resource_flags`
# so it can be compared with the assigned resource state.
# Flags that can be used more than once should be expressed as an array. For
# flags which take no arguments, set the hash value to be undef. In the
# YAML representation you can use `~` or `null` as the value.
#
# @param service_flags
# When a container is created, a systemd unit file for the container service
# is generated using the 'podman generate systemd' command. All flags for the
# command are supported using the 'service_flags' hash parameter, again using
# only the long form of the flag names.
#
# @param command
# Optional command to be used as the container entry point.
#
# @param ensure
# Valid values are 'present' or 'absent'
#
# @param enable
# Status of the automatically generated systemd service for the container.
# Valid values are 'running' or 'stopped'.
#
# @param update
# When `true`, the container will be redeployed when a new container image is
# detected in the container registry. This is done by comparing the digest
# value of the running container image with the digest of the registry image.
# When `false`, the container will only be redeployed when the declared state
# of the puppet resource is changed.
#
# @param ruby
# The absolute path to the ruby binary to use in scripts. The default path is
# '/opt/puppetlabs/puppet/bin/ruby' for Puppetlabs packaged puppet, and
# '/usr/bin/ruby' for all others.
#
# @example
# podman::container { 'jenkins':
# image => 'docker.io/jenkins/jenkins',
# user => 'jenkins',
# flags => {
# publish => [
# '8080:8080',
# '50000:50000',
# ],
# volume => 'jenkins:/var/jenkins_home',
# },
# service_flags => { timeout => '60' },
# }
#
define podman::container (
Optional[String] $image = undef,
Optional[String] $user = undef,
Hash $flags = {},
Hash $service_flags = {},
Optional[String] $command = undef,
Enum['present', 'absent'] $ensure = 'present',
Boolean $enable = true,
Boolean $update = true,
Optional[Stdlib::Unixpath] $ruby = undef,
) {
require podman::install
$installed_ruby = $facts['ruby']['sitedir'] ? {
/^\/opt\/puppetlabs\// => '/opt/puppetlabs/puppet/bin/ruby',
default => '/usr/bin/ruby',
}
$_ruby = pick($ruby, $installed_ruby)
# Add a label of base64 encoded flags defined for the container resource
# This will be used to determine when the resource state is changed
$flags_base64 = base64('encode', inline_template('<%= @flags.to_s %>'), strict)
# Add the default name and a custom label using the base64 encoded flags
if 'label' in $flags {
$label = [] + $flags['label'] + "puppet_resource_flags=${flags_base64}"
$no_label = $flags.delete('label')
} else {
$label = "puppet_resource_flags=${flags_base64}"
$no_label = $flags
}
# If a container name is not set, use the Puppet resource name
$merged_flags = stdlib::merge({ name => $title, label => $label }, $no_label )
$container_name = $merged_flags['name']
# A rootless container will run as the defined user
if $user != undef and $user != '' {
$systemctl = 'systemctl --user '
$requires = [Podman::Rootless[$user]]
$service_unit_file = "${User[$user]['home']}/.config/systemd/user/podman-${container_name}.service"
$_podman_systemd_reload = Exec["podman_systemd_${user}_reload"]
# The handle is used to ensure resources have unique names
$handle = "${user}-${container_name}"
# Set default execution environment for the rootless user
$exec_defaults = {
cwd => User[$user]['home'],
user => $user,
environment => [
"HOME=${User[$user]['home']}",
"XDG_RUNTIME_DIR=/run/user/${User[$user]['uid']}",
"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/${User[$user]['uid']}/bus",
],
}
ensure_resource('podman::rootless', $user, {})
# Reload systemd when service files are updated
ensure_resource('Exec', "podman_systemd_${user}_reload",
{
path => '/sbin:/usr/sbin:/bin:/usr/bin',
command => "${systemctl} daemon-reload",
refreshonly => true,
environment => ["HOME=${User[$user]['home']}", "XDG_RUNTIME_DIR=/run/user/${User[$user]['uid']}"],
cwd => User[$user]['home'],
provider => 'shell',
user => $user,
},
)
} else {
$systemctl = 'systemctl '
$requires = []
$service_unit_file = "/etc/systemd/system/podman-${container_name}.service"
$_podman_systemd_reload = Exec['podman_systemd_reload']
$handle = $container_name
$exec_defaults = {}
# Reload systemd when service files are updated
ensure_resource('Exec', 'podman_systemd_reload',
{
path => '/sbin:/usr/sbin:/bin:/usr/bin',
command => "${systemctl} daemon-reload",
refreshonly => true,
},
)
}
case $ensure {
'present': {
if $image == undef { fail('A source image is required') }
# Detect changes to the defined podman flags and re-deploy if needed
$unless_vcf = @("END"/$L)
if podman container exists ${container_name}
then
saved_resource_flags="\$(podman container inspect ${container_name} \
--format '{{.Config.Labels.puppet_resource_flags}}')"
current_resource_flags="${flags_base64}"
test "\${saved_resource_flags}" = "\${current_resource_flags}"
fi
| END
exec { "verify_container_flags_${handle}":
command => 'true',
provider => 'shell',
unless => $unless_vcf,
notify => Exec["podman_remove_container_${handle}"],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
# Re-deploy when $update is true and the container image has been updated
if $update {
$unless_vci = @("END"/$L)
if podman container exists ${container_name}
then
image_name=\$(podman container inspect ${container_name} --format '{{.ImageName}}')
running_digest=\$(podman image inspect $(podman image inspect \${image_name} --format='{{.ID}}') --format '{{.Digest}}')
latest_digest=\$(skopeo inspect docker://${image} | \
${_ruby} -rjson -e 'puts (JSON.parse(STDIN.read))["Digest"]')
[[ $? -ne 0 ]] && latest_digest=\$(skopeo inspect --no-creds docker://${image} | \
${_ruby} -rjson -e 'puts (JSON.parse(STDIN.read))["Digest"]')
test -z "\${latest_digest}" && exit 0 # Do not update if unable to get latest digest
test "\${running_digest}" = "\${latest_digest}"
fi
| END
exec { "verify_container_image_${handle}":
command => 'true',
provider => 'shell',
unless => $unless_vci,
notify => [Exec["podman_remove_image_${handle}"], Exec["podman_remove_container_${handle}"]],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
} else {
# Re-deploy when $update is false but the resource image has changed
$unless_vci = @("END"/$L)
if podman container exists ${container_name}
then
running=\$(podman container inspect ${container_name} --format '{{.ImageName}}' | awk -F/ '{print \$NF}')
declared=\$(echo "${image}" | awk -F/ '{print \$NF}')
test "\${running}" = "\${declared}" && exit 0
available=\$(skopeo inspect docker://${image} | \
${_ruby} -rjson -e 'puts (JSON.parse(STDIN.read))["Name"]')
test -z "\${available}" && exit 0 # Do not update update if unable to get the new image
exit 1
fi
| END
exec { "verify_container_image_${handle}":
command => 'true',
provider => 'shell',
unless => $unless_vci,
notify => [Exec["podman_remove_image_${handle}"], Exec["podman_remove_container_${handle}"]],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
}
# Try to remove the image, but exit with success regardless
exec { "podman_remove_image_${handle}":
provider => 'shell',
command => "podman rmi ${image} || exit 0",
refreshonly => true,
notify => Exec["podman_create_${handle}"],
require => [$requires, Exec["podman_remove_container_${handle}"]],
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
$command_prc = @("END"/L)
${systemctl} stop podman-${container_name} || true
podman container stop --time 60 ${container_name} || true
podman container rm --force ${container_name} || true
| END
$onlyif_prc = @("END"/L)
test $(podman container inspect --format json ${container_name} |\
${_ruby} -rjson -e 'puts (JSON.parse(STDIN.read))[0]["State"]["Running"]') = true
| END
# Try to stop the container service, then the container directly
exec { "podman_remove_container_${handle}":
provider => 'shell',
command => $command_prc,
onlyif => $onlyif_prc,
refreshonly => true,
notify => Exec["podman_create_${handle}"],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
# Convert $merged_flags hash to usable command arguments
$_flags = $merged_flags.reduce('') |$mem, $flag| {
if $flag[1] =~ String {
"${mem} --${flag[0]} '${flag[1]}'"
} elsif $flag[1] =~ Undef {
"${mem} --${flag[0]}"
} else {
$dup = $flag[1].reduce('') |$mem2, $value| {
"${mem2} --${flag[0]} '${value}'"
}
"${mem} ${dup}"
}
}
# Convert $service_flags hash to command arguments
$_service_flags = $service_flags.reduce('') |$mem, $flag| {
if $flag[1] =~ String {
if $flag[1] == '' {
"${mem} --${flag[0]}"
} else {
"${mem} --${flag[0]} '${flag[1]}'"
}
} elsif $flag[1] =~ Undef {
"${mem} --${flag[0]}"
} else {
$dup = $flag[1].reduce('') |$mem2, $value| {
"${mem2} --${flag[0]} '${value}'"
}
"${mem} ${dup}"
}
}
exec { "podman_create_${handle}":
command => "podman container create ${_flags} ${image} ${command}",
unless => "podman container exists ${container_name}",
notify => Exec["podman_generate_service_${handle}"],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
if $user != undef and $user != '' {
exec { "podman_generate_service_${handle}":
command => "podman generate systemd ${_service_flags} ${container_name} > ${service_unit_file}",
refreshonly => true,
notify => Exec["service_podman_${handle}"],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
# Work-around for managing user systemd services
if $enable {
$action = 'start'; $startup = 'enable'
} else {
$action = 'stop'; $startup = 'disable'
}
$command_sp = @("END"/L)
${systemctl} ${startup} podman-${container_name}.service
${systemctl} ${action} podman-${container_name}.service
| END
$unless_sp = @("END"/L)
${systemctl} is-active podman-${container_name}.service && \
${systemctl} is-enabled podman-${container_name}.service
| END
exec { "service_podman_${handle}":
command => $command_sp,
unless => $unless_sp,
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
} else {
exec { "podman_generate_service_${handle}":
path => '/sbin:/usr/sbin:/bin:/usr/bin',
command => "podman generate systemd ${_service_flags} ${container_name} > ${service_unit_file}",
refreshonly => true,
notify => Service["podman-${handle}"],
}
# Configure the container service per parameters
if $enable {
$state = 'running'; $startup = 'true'
} else {
$state = 'stopped'; $startup = 'false'
}
service { "podman-${handle}":
ensure => $state,
enable => $startup,
}
}
}
default: {
$command_sp = @("END"/L)
${systemctl} stop podman-${container_name}
${systemctl} disable podman-${container_name}
| END
$onlyif_sp = @("END"/$L)
test "\$(${systemctl} is-active podman-${container_name} 2>&1)" = "active" -o \
"\$(${systemctl} is-enabled podman-${container_name} 2>&1)" = "enabled"
| END
exec { "service_podman_${handle}":
command => $command_sp,
onlyif => $onlyif_sp,
notify => Exec["podman_remove_container_${handle}"],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
exec { "podman_remove_container_${handle}":
command => "podman container rm --force ${container_name}",
unless => "podman container exists ${container_name}; test $? -eq 1",
notify => Exec["podman_remove_image_${handle}"],
require => $requires,
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
# Try to remove the image, but exit with success regardless
exec { "podman_remove_image_${handle}":
provider => 'shell',
command => "podman rmi ${image} || exit 0",
refreshonly => true,
require => [$requires, Exec["podman_remove_container_${handle}"]],
path => '/sbin:/usr/sbin:/bin:/usr/bin',
* => $exec_defaults,
}
file { $service_unit_file:
ensure => absent,
require => [$requires, Exec["service_podman_${handle}"]],
notify => $_podman_systemd_reload,
}
}
}
}