Debian Codegraph @

ansible_collections/containers/podman/plugins/modules/podman_image.py

raw
1 # Copyright (c) 2018 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import absolute_import, division, print_function
5
6 __metaclass__ = type
7
8
9 DOCUMENTATION = r"""
10 module: podman_image
11 author:
12 - Sagi Shnaidman (@sshnaidm)
13 short_description: Pull images for use by podman
14 notes: []
15 description:
16 - Build, pull, or push images using Podman.
17 options:
18 arch:
19 description:
20 - CPU architecture for the container image
21 type: str
22 platform:
23 description:
24 - Platform for the container image (e.g. C(linux/amd64), C(linux/arm64)).
25 - Specify the platform for selecting the image when pulling or building.
26 - Mutually exclusive with C(arch).
27 type: str
28 name:
29 description:
30 - Name of the image to pull, push, or delete. It may contain a tag using the format C(image:tag).
31 required: True
32 type: str
33 executable:
34 description:
35 - Path to C(podman) executable if it is not in the C($PATH) on the machine running C(podman).
36 default: 'podman'
37 type: str
38 ca_cert_dir:
39 description:
40 - Path to directory containing TLS certificates and keys to use.
41 type: 'path'
42 tag:
43 description:
44 - Tag of the image to pull, push, or delete.
45 default: "latest"
46 type: str
47 pull:
48 description: Whether or not to pull the image.
49 default: True
50 type: bool
51 pull_extra_args:
52 description:
53 - Extra arguments to pass to the pull command.
54 type: str
55 push:
56 description: Whether or not to push an image.
57 default: False
58 type: bool
59 path:
60 description: Path to the build context directory.
61 type: str
62 force:
63 description:
64 - Whether or not to force push or pull an image.
65 - When building, force the build even if the image already exists.
66 type: bool
67 default: False
68 state:
69 description:
70 - Whether an image should be present, absent, or built.
71 default: "present"
72 type: str
73 choices:
74 - present
75 - absent
76 - build
77 - quadlet
78 validate_certs:
79 description:
80 - Require HTTPS and validate certificates when pulling or pushing.
81 Also used during build if a pull or push is necessary.
82 type: bool
83 aliases:
84 - tlsverify
85 - tls_verify
86 password:
87 description:
88 - Password to use when authenticating to remote registries.
89 type: str
90 username:
91 description:
92 - username to use when authenticating to remote registries.
93 type: str
94 auth_file:
95 description:
96 - Path to file containing authorization credentials to the remote registry.
97 aliases:
98 - authfile
99 type: path
100 build:
101 description: Arguments that control image build.
102 type: dict
103 default: {}
104 aliases:
105 - build_args
106 - buildargs
107 suboptions:
108 container_file:
109 description:
110 - Content of the Containerfile to use for building the image.
111 Mutually exclusive with the C(file) option which is path to the existing Containerfile.
112 type: str
113 file:
114 description:
115 - Path to the Containerfile if it is not in the build context directory.
116 Mutually exclusive with the C(container_file) option.
117 type: path
118 volume:
119 description:
120 - Specify multiple volume / mount options to mount one or more mounts to a container.
121 type: list
122 elements: str
123 annotation:
124 description:
125 - Dictionary of key=value pairs to add to the image. Only works with OCI images.
126 Ignored for Docker containers.
127 type: dict
128 force_rm:
129 description:
130 - Always remove intermediate containers after a build, even if the build is unsuccessful.
131 type: bool
132 default: False
133 format:
134 description:
135 - Format of the built image.
136 type: str
137 choices:
138 - docker
139 - oci
140 default: "oci"
141 cache:
142 description:
143 - Whether or not to use cached layers when building an image
144 type: bool
145 default: True
146 rm:
147 description: Remove intermediate containers after a successful build
148 type: bool
149 default: True
150 extra_args:
151 description:
152 - Extra args to pass to build, if executed. Does not idempotently check for new build args.
153 type: str
154 target:
155 description:
156 - Specify the target build stage to build.
157 type: str
158 push_args:
159 description: Arguments that control pushing images.
160 type: dict
161 default: {}
162 suboptions:
163 ssh:
164 description:
165 - SSH options to use when pushing images with SCP transport.
166 type: str
167 compress:
168 description:
169 - Compress tarball image layers when pushing to a directory using the 'dir' transport.
170 type: bool
171 format:
172 description:
173 - Manifest type to use when pushing an image using the 'dir' transport (default is manifest type of source)
174 type: str
175 choices:
176 - oci
177 - v2s1
178 - v2s2
179 remove_signatures:
180 description: Discard any pre-existing signatures in the image
181 type: bool
182 sign_by:
183 description:
184 - Path to a key file to use to sign the image.
185 type: str
186 dest:
187 description: Path or URL where image will be pushed.
188 type: str
189 aliases:
190 - destination
191 transport:
192 description:
193 - Transport to use when pushing in image. If no transport is set, will attempt to push to a remote registry
194 type: str
195 choices:
196 - dir
197 - docker-archive
198 - docker-daemon
199 - oci-archive
200 - ostree
201 - docker
202 - scp
203 extra_args:
204 description:
205 - Extra args to pass to push, if executed. Does not idempotently check for new push args.
206 type: str
207 quadlet_dir:
208 description:
209 - Path to the directory to write quadlet file in.
210 By default, it will be set as C(/etc/containers/systemd/) for root user,
211 C(~/.config/containers/systemd/) for non-root users.
212 type: path
213 required: false
214 quadlet_filename:
215 description:
216 - Name of quadlet file to write. By default it takes image name without prefixes and tags.
217 type: str
218 quadlet_file_mode:
219 description:
220 - The permissions of the quadlet file.
221 - The O(quadlet_file_mode) can be specified as octal numbers or as a symbolic mode
222 (for example, V(u+rwx) or V(u=rw,g=r,o=r)).
223 For octal numbers format, you must either add a leading zero so that Ansible's YAML parser knows it is an
224 octal number (like V(0644) or V(01777)) or quote it (like V('644') or V('1777')) so Ansible receives a string
225 and can do its own conversion from string into number. Giving Ansible a number without following one of these
226 rules will end up with a decimal number which will have unexpected results.
227 - If O(quadlet_file_mode) is not specified and the quadlet file B(does not) exist, the default V('0640') mask
228 will be used
229 when setting the mode for the newly created file.
230 - If O(quadlet_file_mode) is not specified and the quadlet file B(does) exist, the mode of the existing file
231 will be used.
232 - Specifying O(quadlet_file_mode) is the best way to ensure files are created with the correct permissions.
233 type: raw
234 required: false
235 quadlet_options:
236 description:
237 - Options for the quadlet file. Provide missing in usual network args
238 options as a list of lines to add.
239 type: list
240 elements: str
241 required: false
242 """
243
244 EXAMPLES = r"""
245 - name: Pull an image
246 containers.podman.podman_image:
247 name: quay.io/bitnami/wildfly
248
249 - name: Remove an image
250 containers.podman.podman_image:
251 name: quay.io/bitnami/wildfly
252 state: absent
253
254 - name: Remove an image with image id
255 containers.podman.podman_image:
256 name: 0e901e68141f
257 state: absent
258
259 - name: Pull a specific version of an image
260 containers.podman.podman_image:
261 name: redis
262 tag: 4
263
264 - name: Build a basic OCI image
265 containers.podman.podman_image:
266 name: nginx
267 path: /path/to/build/dir
268
269 - name: Build a basic OCI image with advanced parameters
270 containers.podman.podman_image:
271 name: nginx
272 path: /path/to/build/dir
273 build:
274 cache: no
275 force_rm: true
276 format: oci
277 annotation:
278 app: nginx
279 function: proxy
280 info: Load balancer for my cool app
281 extra_args: "--build-arg KEY=value"
282
283 - name: Build a Docker formatted image
284 containers.podman.podman_image:
285 name: nginx
286 path: /path/to/build/dir
287 build:
288 format: docker
289
290 - name: Build and push an image using existing credentials
291 containers.podman.podman_image:
292 name: nginx
293 path: /path/to/build/dir
294 push: true
295 push_args:
296 dest: quay.io/acme
297
298 - name: Build and push an image using an auth file
299 containers.podman.podman_image:
300 name: nginx
301 push: true
302 auth_file: /etc/containers/auth.json
303 push_args:
304 dest: quay.io/acme
305
306 - name: Build and push an image using username and password
307 containers.podman.podman_image:
308 name: nginx
309 push: true
310 username: bugs
311 password: "{{ vault_registry_password }}"
312 push_args:
313 dest: quay.io/acme
314
315 - name: Build and push an image to multiple registries
316 containers.podman.podman_image:
317 name: "{{ item }}"
318 path: /path/to/build/dir
319 push: true
320 auth_file: /etc/containers/auth.json
321 loop:
322 - quay.io/acme/nginx
323 - docker.io/acme/nginx
324
325 - name: Build and push an image to multiple registries with separate parameters
326 containers.podman.podman_image:
327 name: "{{ item.name }}"
328 tag: "{{ item.tag }}"
329 path: /path/to/build/dir
330 push: true
331 auth_file: /etc/containers/auth.json
332 push_args:
333 dest: "{{ item.dest }}"
334 loop:
335 - name: nginx
336 tag: 4
337 dest: docker.io/acme
338
339 - name: nginx
340 tag: 3
341 dest: docker.io/acme
342
343 - name: Push image to a remote host via scp transport
344 containers.podman.podman_image:
345 name: testimage
346 pull: false
347 push: true
348 push_args:
349 dest: user@server
350 transport: scp
351
352 - name: Pull an image for a specific CPU architecture
353 containers.podman.podman_image:
354 name: nginx
355 arch: amd64
356
357 - name: Pull an image for a specific platform (e.g. x86 on M-series Mac)
358 containers.podman.podman_image:
359 name: nginx
360 platform: linux/amd64
361
362 - name: Build a container from file inline
363 containers.podman.podman_image:
364 name: mycustom_image
365 state: build
366 build:
367 container_file: |-
368 FROM alpine:latest
369 CMD echo "Hello, World!"
370
371 - name: Create a quadlet file for an image
372 containers.podman.podman_image:
373 name: docker.io/library/alpine:latest
374 state: quadlet
375 quadlet_dir: /etc/containers/systemd
376 quadlet_filename: alpine-latest
377 quadlet_file_mode: '0640'
378 quadlet_options:
379 - Variant=arm/v7
380 - |
381 [Install]
382 WantedBy=default.target
383 """
384
385 RETURN = r"""
386 image:
387 description:
388 - Image inspection results for the image that was pulled, pushed, or built.
389 returned: success
390 type: dict
391 sample: [
392 {
393 "Id": "6d1ef012b5674ad8a127ecfa9b5e6f5178d171b90ee462846974177fd9bdd39f",
394 "Digest": "sha256:8421d9a84432575381bfabd248f1eb56f3aa21d9d7cd2511583c68c9b7511d10",
395 "RepoTags": [
396 "docker.io/library/alpine:3.7"
397 ],
398 "RepoDigests": [
399 "docker.io/library/alpine@sha256:8421...",
400 "docker.io/library/alpine@sha256:9225..."
401 ],
402 "Parent": "",
403 "Comment": "",
404 "Created": "2019-03-07T22:19:53.447205048Z",
405 "Config": {
406 "Env": [
407 "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
408 ],
409 "Cmd": [
410 "/bin/sh"
411 ],
412 "ArgsEscaped": true
413 },
414 "Version": "18.06.1-ce",
415 "Author": "",
416 "Architecture": "amd64",
417 "Os": "linux",
418 "Size": 4467084,
419 "VirtualSize": 4467084,
420 "GraphDriver": {
421 "Name": "overlay",
422 "Data": {
423 "UpperDir": "/home/user/.local/share/containers/storage/overlay/3fc6.../diff",
424 "WorkDir": "/home/user/.local/share/containers/storage/overlay/3fc6.../work"
425 }
426 },
427 "RootFS": {
428 "Type": "layers",
429 "Layers": [
430 "sha256:3fc6..."
431 ]
432 },
433 "Labels": null,
434 "Annotations": {},
435 "ManifestType": "application/vnd.docker.distribution.manifest.v2+json",
436 "User": "",
437 "History": [
438 {
439 "created": "2019-03-07T22:19:53.313789681Z",
440 "created_by": "/bin/sh -c #(nop) ADD file:aa17928... in / "
441 },
442 {
443 "created": "2019-03-07T22:19:53.447205048Z",
444 "created_by": "/bin/sh -c #(nop) CMD [\"/bin/sh\"]",
445 "empty_layer": true
446 }
447 ],
448 "NamesHistory": [
449 "docker.io/library/alpine:3.7"
450 ]
451 }
452 ]
453
454 """
455
456 from ansible.module_utils.basic import AnsibleModule
457 from ..module_utils.podman.quadlet import (
458 create_quadlet_state,
459 )
460 from ..module_utils.podman.podman_image_lib import (
461 PodmanImageManager,
462 )
463
464
465 def main():
466 module = AnsibleModule(
467 argument_spec=dict(
468 name=dict(type="str", required=True),
469 arch=dict(type="str"),
470 platform=dict(type="str"),
471 tag=dict(type="str", default="latest"),
472 pull=dict(type="bool", default=True),
473 pull_extra_args=dict(type="str"),
474 push=dict(type="bool", default=False),
475 path=dict(type="str"),
476 force=dict(type="bool", default=False),
477 state=dict(
478 type="str",
479 default="present",
480 choices=["absent", "present", "build", "quadlet"],
481 ),
482 validate_certs=dict(type="bool", aliases=["tlsverify", "tls_verify"]),
483 executable=dict(type="str", default="podman"),
484 auth_file=dict(type="path", aliases=["authfile"]),
485 username=dict(type="str"),
486 password=dict(type="str", no_log=True),
487 ca_cert_dir=dict(type="path"),
488 quadlet_dir=dict(type="path", required=False),
489 quadlet_filename=dict(type="str"),
490 quadlet_file_mode=dict(type="raw", required=False),
491 quadlet_options=dict(type="list", elements="str", required=False),
492 build=dict(
493 type="dict",
494 aliases=["build_args", "buildargs"],
495 default={},
496 options=dict(
497 annotation=dict(type="dict"),
498 force_rm=dict(type="bool", default=False),
499 file=dict(type="path"),
500 container_file=dict(type="str"),
501 format=dict(type="str", choices=["oci", "docker"], default="oci"),
502 cache=dict(type="bool", default=True),
503 rm=dict(type="bool", default=True),
504 volume=dict(type="list", elements="str"),
505 extra_args=dict(type="str"),
506 target=dict(type="str"),
507 ),
508 ),
509 push_args=dict(
510 type="dict",
511 default={},
512 options=dict(
513 ssh=dict(type="str"),
514 compress=dict(type="bool"),
515 format=dict(type="str", choices=["oci", "v2s1", "v2s2"]),
516 remove_signatures=dict(type="bool"),
517 sign_by=dict(type="str"),
518 dest=dict(
519 type="str",
520 aliases=["destination"],
521 ),
522 extra_args=dict(type="str"),
523 transport=dict(
524 type="str",
525 choices=[
526 "dir",
527 "docker-archive",
528 "docker-daemon",
529 "oci-archive",
530 "ostree",
531 "docker",
532 "scp",
533 ],
534 ),
535 ),
536 ),
537 ),
538 supports_check_mode=True,
539 required_together=(["username", "password"],),
540 mutually_exclusive=(
541 ["auth_file", "username"],
542 ["auth_file", "password"],
543 ["arch", "platform"],
544 ),
545 )
546
547 # Handle quadlet state separately
548 if module.params["state"] == "quadlet": # type: ignore
549 results = create_quadlet_state(module, "image")
550 module.exit_json(**results)
551
552 try:
553 manager = PodmanImageManager(module)
554 results = manager.execute()
555 module.exit_json(**results)
556 except Exception as e:
557 module.fail_json(msg=f"Failed to manage image: {str(e)}", exception=str(e))
558
559
560 if __name__ == "__main__":
561 main()