Migrated to containers.podman

This commit is contained in:
Ansible Core Team 2020-03-09 09:40:26 +00:00 committed by Matt Martz
parent 13bd868f59
commit 38c652712c
35 changed files with 0 additions and 2347 deletions

View file

@ -1,19 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2019 Ansible Project
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
def run_podman_command(module, executable='podman', args=None, expected_rc=0, ignore_errors=False):
if not isinstance(executable, list):
command = [executable]
if args is not None:
command.extend(args)
rc, out, err = module.run_command(command)
if not ignore_errors and rc != expected_rc:
module.fail_json(
msg='Failed to run {command} {args}: {err}'.format(
command=command, args=args, err=err))
return rc, out, err

View file

@ -1,410 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2019 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
module: podman_container_info
author:
- Sagi Shnaidman (@sshnaidm)
- Emilien Macchi (@EmilienM)
version_added: '2.10'
short_description: Gather facts about containers using podman
notes:
- Podman may require elevated privileges in order to run properly.
description:
- Gather facts about containers using C(podman)
requirements:
- "Podman installed on host"
options:
name:
description:
- List of container names to gather facts about. If no name is given
return facts about all containers.
type: list
elements: str
executable:
description:
- Path to C(podman) executable if it is not in the C($PATH) on the
machine running C(podman)
default: 'podman'
type: str
"""
EXAMPLES = """
- name: Gather facts for all containers
podman_container_info:
- name: Gather facts on a specific container
podman_container_info:
name: web1
- name: Gather facts on several containers
podman_container_info:
name:
- redis
- web1
"""
RETURN = """
containers:
description: Facts from all or specificed containers
returned: always
type: list
elements: dict
sample: [
{
"Id": "c5c39f9b80a6ea2ad665aa9946435934e478a0c5322da835f3883872f",
"Created": "2019-10-01T12:51:00.233106443Z",
"Path": "dumb-init",
"Args": [
"--single-child",
"--",
"kolla_start"
],
"State": {
"OciVersion": "1.0.1-dev",
"Status": "configured",
"Running": false,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 0,
"ExitCode": 0,
"Error": "",
"StartedAt": "0001-01-01T00:00:00Z",
"FinishedAt": "0001-01-01T00:00:00Z",
"Healthcheck": {
"Status": "",
"FailingStreak": 0,
"Log": null
}
},
"Image": "0e267acda67d0ebd643e900d820a91b961d859743039e620191ca1",
"ImageName": "docker.io/tripleomaster/centos-haproxy:latest",
"Rootfs": "",
"Pod": "",
"ResolvConfPath": "",
"HostnamePath": "",
"HostsPath": "",
"OCIRuntime": "runc",
"Name": "haproxy",
"RestartCount": 0,
"Driver": "overlay",
"MountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c78,c866",
"ProcessLabel": "system_u:system_r:svirt_lxc_net_t:s0:c785,c866",
"AppArmorProfile": "",
"EffectiveCaps": [
"CAP_CHOWN",
"CAP_DAC_OVERRIDE",
"CAP_FSETID",
"CAP_FOWNER",
"CAP_MKNOD",
"CAP_NET_RAW",
"CAP_SETGID",
"CAP_SETUID",
"CAP_SETFCAP",
"CAP_SETPCAP",
"CAP_NET_BIND_SERVICE",
"CAP_SYS_CHROOT",
"CAP_KILL",
"CAP_AUDIT_WRITE"
],
"BoundingCaps": [
"CAP_CHOWN",
"CAP_DAC_OVERRIDE",
"CAP_FSETID",
"CAP_FOWNER",
"CAP_MKNOD",
"CAP_NET_RAW",
"CAP_SETGID",
"CAP_SETUID",
"CAP_SETFCAP",
"CAP_SETPCAP",
"CAP_NET_BIND_SERVICE",
"CAP_SYS_CHROOT",
"CAP_KILL",
"CAP_AUDIT_WRITE"
],
"ExecIDs": [],
"GraphDriver": {
"Name": "overlay"
},
"Mounts": [],
"Dependencies": [],
"NetworkSettings": {
"Bridge": "",
"SandboxID": "",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": [],
"SandboxKey": "",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": ""
},
"ExitCommand": [
"/usr/bin/podman",
"--root",
"/var/lib/containers/storage",
"--runroot",
"/var/run/containers/storage",
"--log-level",
"error",
"--cgroup-manager",
"systemd",
"--tmpdir",
"/var/run/libpod",
"--runtime",
"runc",
"--storage-driver",
"overlay",
"--events-backend",
"journald",
"container",
"cleanup",
"c9e813703f9b80a6ea2ad665aa9946435934e478a0c5322da835f3883872f"
],
"Namespace": "",
"IsInfra": false,
"Config": {
"Hostname": "c5c39e813703",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"PATH=/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"TERM=xterm",
"HOSTNAME=",
"container=oci",
"KOLLA_INSTALL_METATYPE=rdo",
"KOLLA_BASE_DISTRO=centos",
"KOLLA_INSTALL_TYPE=binary",
"KOLLA_DISTRO_PYTHON_VERSION=2.7",
"KOLLA_BASE_ARCH=x86_64"
],
"Cmd": [
"kolla_start"
],
"Image": "docker.io/tripleomaster/centos-haproxy:latest",
"Volumes": null,
"WorkingDir": "/",
"Entrypoint": "dumb-init --single-child --",
"OnBuild": null,
"Labels": {
"build-date": "20190919",
"kolla_version": "8.1.0",
"name": "haproxy",
"org.label-schema.build-date": "20190801",
"org.label-schema.license": "GPLv2",
"org.label-schema.name": "CentOS Base Image",
"org.label-schema.schema-version": "1.0",
"org.label-schema.vendor": "CentOS"
},
"Annotations": {
"io.kubernetes.cri-o.ContainerType": "sandbox",
"io.kubernetes.cri-o.TTY": "false",
"io.podman.annotations.autoremove": "FALSE",
"io.podman.annotations.init": "FALSE",
"io.podman.annotations.privileged": "FALSE",
"io.podman.annotations.publish-all": "FALSE"
},
"StopSignal": 15
},
"HostConfig": {
"Binds": [],
"ContainerIDFile": "",
"LogConfig": {
"Type": "k8s-file",
"Config": null
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": [],
"CapDrop": [],
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": [],
"GroupAdd": [],
"IpcMode": "",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": [],
"Tmpfs": {},
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 65536000,
"Runtime": "oci",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": -1,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": [
{
"Name": "RLIMIT_NOFILE",
"Soft": 1048576,
"Hard": 1048576
},
{
"Name": "RLIMIT_NPROC",
"Soft": 1048576,
"Hard": 1048576
}
],
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0
}
}
]
"""
import json
from ansible.module_utils.basic import AnsibleModule
def get_containers_facts(module, executable, name):
"""Collect containers facts for all containers or for specified in 'name'.
Arguments:
module {AnsibleModule} -- instance of AnsibleModule
executable {string} -- binary to execute when inspecting containers
name {list} -- list of names or None in case of all containers
Returns:
list of containers info, stdout, stderr
"""
if not name:
all_names = [executable, 'container', 'ls', '-q', '-a']
rc, out, err = module.run_command(all_names)
if rc != 0:
module.fail_json(msg="Unable to get list of containers: %s" % err)
name = out.split()
if not name:
return [], out, err
command = [executable, 'container', 'inspect']
command.extend(name)
rc, out, err = module.run_command(command)
if rc == 0:
json_out = json.loads(out) if out else None
if json_out is None:
return [], out, err
return json_out, out, err
if rc != 0 and 'no such ' in err:
if len(name) < 2:
return [], out, err
return cycle_over(module, executable, name)
module.fail_json(msg="Unable to gather info for %s: %s" % (",".join(name), err))
def cycle_over(module, executable, name):
"""Inspect each container in a cycle in case some of them don't exist.
Arguments:
module {AnsibleModule} -- instance of AnsibleModule
executable {string} -- binary to execute when inspecting containers
name {list} -- list of containers names to inspect
Returns:
list of containers info, stdout as empty, stderr
"""
inspection = []
stderrs = []
for container in name:
command = [executable, 'container', 'inspect', container]
rc, out, err = module.run_command(command)
if rc != 0 and 'no such ' not in err:
module.fail_json(msg="Unable to gather info for %s: %s" % (container, err))
if rc == 0 and out:
json_out = json.loads(out)
if json_out:
inspection += json_out
stderrs.append(err)
return inspection, "", "\n".join(stderrs)
def main():
module = AnsibleModule(
argument_spec={
'executable': {'type': 'str', 'default': 'podman'},
'name': {'type': 'list', 'elements': 'str'},
},
supports_check_mode=True,
)
name = module.params['name']
executable = module.get_bin_path(module.params['executable'], required=True)
inspect_results, out, err = get_containers_facts(module, executable, name)
results = {
"changed": False,
"containers": inspect_results,
"stderr": err
}
module.exit_json(**results)
if __name__ == '__main__':
main()

View file

@ -1,729 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
module: podman_image
author:
- Sam Doran (@samdoran)
version_added: '2.8'
short_description: Pull images for use by podman
notes: []
description:
- Build, pull, or push images using Podman.
options:
name:
description:
- Name of the image to pull, push, or delete. It may contain a tag using the format C(image:tag).
required: True
executable:
description:
- Path to C(podman) executable if it is not in the C($PATH) on the machine running C(podman)
default: 'podman'
type: str
ca_cert_dir:
description:
- Path to directory containing TLS certificates and keys to use
type: 'path'
tag:
description:
- Tag of the image to pull, push, or delete.
default: "latest"
pull:
description: Whether or not to pull the image.
default: True
push:
description: Whether or not to push an image.
default: False
path:
description: Path to directory containing the build file.
force:
description:
- Whether or not to force push or pull an image. When building, force the build even if the image already exists.
state:
description:
- Whether an image should be present, absent, or built.
default: "present"
choices:
- present
- absent
- build
validate_certs:
description:
- Require HTTPS and validate certificates when pulling or pushing. Also used during build if a pull or push is necessary.
default: True
aliases:
- tlsverify
- tls_verify
password:
description:
- Password to use when authenticating to remote registries.
type: str
username:
description:
- username to use when authenticating to remote registries.
type: str
auth_file:
description:
- Path to file containing authorization credentials to the remote registry
aliases:
- authfile
build:
description: Arguments that control image build.
aliases:
- build_args
- buildargs
suboptions:
annotation:
description:
- Dictionary of key=value pairs to add to the image. Only works with OCI images. Ignored for Docker containers.
type: str
force_rm:
description:
- Always remove intermediate containers after a build, even if the build is unsuccessful.
type: bool
default: False
format:
description:
- Format of the built image.
choices:
- docker
- oci
default: "oci"
cache:
description:
- Whether or not to use cached layers when building an image
type: bool
default: True
rm:
description: Remove intermediate containers after a successful build
type: bool
default: True
push_args:
description: Arguments that control pushing images.
suboptions:
compress:
description:
- Compress tarball image layers when pushing to a directory using the 'dir' transport.
type: bool
format:
description:
- Manifest type to use when pushing an image using the 'dir' transport (default is manifest type of source)
choices:
- oci
- v2s1
- v2s2
remove_signatures:
description: Discard any pre-existing signatures in the image
type: bool
sign_by:
description:
- Path to a key file to use to sign the image.
dest:
description: Path or URL where image will be pushed.
transport:
description:
- Transport to use when pushing in image. If no transport is set, will attempt to push to a remote registry.
choices:
- dir
- docker-archive
- docker-daemon
- oci-archive
- ostree
"""
EXAMPLES = """
- name: Pull an image
podman_image:
name: quay.io/bitnami/wildfly
- name: Remove an image
podman_image:
name: quay.io/bitnami/wildfly
state: absent
- name: Pull a specific version of an image
podman_image:
name: redis
tag: 4
- name: Build a basic OCI image
podman_image:
name: nginx
path: /path/to/build/dir
- name: Build a basic OCI image with advanced parameters
podman_image:
name: nginx
path: /path/to/build/dir
build:
cache: no
force_rm: yes
format: oci
annotation:
app: nginx
function: proxy
info: Load balancer for my cool app
- name: Build a Docker formatted image
podman_image:
name: nginx
path: /path/to/build/dir
build:
format: docker
- name: Build and push an image using existing credentials
podman_image:
name: nginx
path: /path/to/build/dir
push: yes
push_args:
dest: quay.io/acme
- name: Build and push an image using an auth file
podman_image:
name: nginx
push: yes
auth_file: /etc/containers/auth.json
push_args:
dest: quay.io/acme
- name: Build and push an image using username and password
podman_image:
name: nginx
push: yes
username: bugs
password: "{{ vault_registry_password }}"
push_args:
dest: quay.io/acme
- name: Build and push an image to multiple registries
podman_image:
name: "{{ item }}"
path: /path/to/build/dir
push: yes
auth_file: /etc/containers/auth.json
loop:
- quay.io/acme/nginx
- docker.io/acme/nginx
- name: Build and push an image to multiple registries with separate parameters
podman_image:
name: "{{ item.name }}"
tag: "{{ item.tag }}"
path: /path/to/build/dir
push: yes
auth_file: /etc/containers/auth.json
push_args:
dest: "{{ item.dest }}"
loop:
- name: nginx
tag: 4
dest: docker.io/acme
- name: nginx
tag: 3
dest: docker.io/acme
"""
RETURN = """
image:
description:
- Image inspection results for the image that was pulled, pushed, or built.
returned: success
type: dict
sample: [
{
"Annotations": {},
"Architecture": "amd64",
"Author": "",
"Comment": "from Bitnami with love",
"ContainerConfig": {
"Cmd": [
"/run.sh"
],
"Entrypoint": [
"/app-entrypoint.sh"
],
"Env": [
"PATH=/opt/bitnami/java/bin:/opt/bitnami/wildfly/bin:/opt/bitnami/nami/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"IMAGE_OS=debian-9",
"NAMI_VERSION=1.0.0-1",
"GPG_KEY_SERVERS_LIST=ha.pool.sks-keyservers.net",
"TINI_VERSION=v0.13.2",
"TINI_GPG_KEY=595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7",
"GOSU_VERSION=1.10",
"GOSU_GPG_KEY=B42F6819007F00F88E364FD4036A9C25BF357DD4",
"BITNAMI_IMAGE_VERSION=16.0.0-debian-9-r27",
"BITNAMI_PKG_CHMOD=-R g+rwX",
"BITNAMI_PKG_EXTRA_DIRS=/home/wildfly",
"HOME=/",
"BITNAMI_APP_NAME=wildfly",
"NAMI_PREFIX=/.nami",
"WILDFLY_HOME=/home/wildfly",
"WILDFLY_JAVA_HOME=",
"WILDFLY_JAVA_OPTS=",
"WILDFLY_MANAGEMENT_HTTP_PORT_NUMBER=9990",
"WILDFLY_PASSWORD=bitnami",
"WILDFLY_PUBLIC_CONSOLE=true",
"WILDFLY_SERVER_AJP_PORT_NUMBER=8009",
"WILDFLY_SERVER_HTTP_PORT_NUMBER=8080",
"WILDFLY_SERVER_INTERFACE=0.0.0.0",
"WILDFLY_USERNAME=user",
"WILDFLY_WILDFLY_HOME=/home/wildfly",
"WILDFLY_WILDFLY_OPTS=-Dwildfly.as.deployment.ondemand=false"
],
"ExposedPorts": {
"8080/tcp": {},
"9990/tcp": {}
},
"Labels": {
"maintainer": "Bitnami <containers@bitnami.com>"
},
"User": "1001"
},
"Created": "2019-04-10T05:48:03.553887623Z",
"Digest": "sha256:5a8ab28e314c2222de3feaf6dac94a0436a37fc08979d2722c99d2bef2619a9b",
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/containers/storage/overlay/142c1beadf1bb09fbd929465ec98c9dca3256638220450efb4214727d0d0680e/diff:/var/lib/containers/s",
"MergedDir": "/var/lib/containers/storage/overlay/9aa10191f5bddb59e28508e721fdeb43505e5b395845fa99723ed787878dbfea/merged",
"UpperDir": "/var/lib/containers/storage/overlay/9aa10191f5bddb59e28508e721fdeb43505e5b395845fa99723ed787878dbfea/diff",
"WorkDir": "/var/lib/containers/storage/overlay/9aa10191f5bddb59e28508e721fdeb43505e5b395845fa99723ed787878dbfea/work"
},
"Name": "overlay"
},
"History": [
{
"comment": "from Bitnami with love",
"created": "2019-04-09T22:27:40.659377677Z"
},
{
"created": "2019-04-09T22:38:53.86336555Z",
"created_by": "/bin/sh -c #(nop) LABEL maintainer=Bitnami <containers@bitnami.com>",
"empty_layer": true
},
{
"created": "2019-04-09T22:38:54.022778765Z",
"created_by": "/bin/sh -c #(nop) ENV IMAGE_OS=debian-9",
"empty_layer": true
},
],
"Id": "ace34da54e4af2145e1ad277005adb235a214e4dfe1114c2db9ab460b840f785",
"Labels": {
"maintainer": "Bitnami <containers@bitnami.com>"
},
"ManifestType": "application/vnd.docker.distribution.manifest.v1+prettyjws",
"Os": "linux",
"Parent": "",
"RepoDigests": [
"quay.io/bitnami/wildfly@sha256:5a8ab28e314c2222de3feaf6dac94a0436a37fc08979d2722c99d2bef2619a9b"
],
"RepoTags": [
"quay.io/bitnami/wildfly:latest"
],
"RootFS": {
"Layers": [
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
""
],
"Type": "layers"
},
"Size": 466180019,
"User": "1001",
"Version": "18.09.3",
"VirtualSize": 466180019
}
]
"""
import json
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.podman.common import run_podman_command
class PodmanImageManager(object):
def __init__(self, module, results):
super(PodmanImageManager, self).__init__()
self.module = module
self.results = results
self.name = self.module.params.get('name')
self.executable = self.module.get_bin_path(module.params.get('executable'), required=True)
self.tag = self.module.params.get('tag')
self.pull = self.module.params.get('pull')
self.push = self.module.params.get('push')
self.path = self.module.params.get('path')
self.force = self.module.params.get('force')
self.state = self.module.params.get('state')
self.validate_certs = self.module.params.get('validate_certs')
self.auth_file = self.module.params.get('auth_file')
self.username = self.module.params.get('username')
self.password = self.module.params.get('password')
self.ca_cert_dir = self.module.params.get('ca_cert_dir')
self.build = self.module.params.get('build')
self.push_args = self.module.params.get('push_args')
repo, repo_tag = parse_repository_tag(self.name)
if repo_tag:
self.name = repo
self.tag = repo_tag
self.image_name = '{name}:{tag}'.format(name=self.name, tag=self.tag)
if self.state in ['present', 'build']:
self.present()
if self.state in ['absent']:
self.absent()
def _run(self, args, expected_rc=0, ignore_errors=False):
return run_podman_command(
module=self.module,
executable=self.executable,
args=args,
expected_rc=expected_rc,
ignore_errors=ignore_errors)
def _get_id_from_output(self, lines, startswith=None, contains=None, split_on=' ', maxsplit=1):
layer_ids = []
for line in lines.splitlines():
if startswith and line.startswith(startswith) or contains and contains in line:
splitline = line.rsplit(split_on, maxsplit)
layer_ids.append(splitline[1])
# Podman 1.4 changed the output to only include the layer id when run in quiet mode
if not layer_ids:
layer_ids = lines.splitlines()
return(layer_ids[-1])
def present(self):
image = self.find_image()
if not image or self.force:
if self.path:
# Build the image
self.results['actions'].append('Built image {image_name} from {path}'.format(image_name=self.image_name, path=self.path))
self.results['changed'] = True
if not self.module.check_mode:
self.results['image'] = self.build_image()
else:
# Pull the image
self.results['actions'].append('Pulled image {image_name}'.format(image_name=self.image_name))
self.results['changed'] = True
if not self.module.check_mode:
self.results['image'] = self.pull_image()
if self.push:
# Push the image
if '/' in self.image_name:
push_format_string = 'Pushed image {image_name}'
else:
push_format_string = 'Pushed image {image_name} to {dest}'
self.results['actions'].append(push_format_string.format(image_name=self.image_name, dest=self.push_args['dest']))
self.results['changed'] = True
if not self.module.check_mode:
self.results['image'] = self.push_image()
def absent(self):
image = self.find_image()
if image:
self.results['actions'].append('Removed image {name}'.format(name=self.name))
self.results['changed'] = True
self.results['image']['state'] = 'Deleted'
if not self.module.check_mode:
self.remove_image()
def find_image(self, image_name=None):
if image_name is None:
image_name = self.image_name
args = ['image', 'ls', image_name, '--format', 'json']
rc, images, err = self._run(args, ignore_errors=True)
if len(images) > 0:
return json.loads(images)
else:
return None
def inspect_image(self, image_name=None):
if image_name is None:
image_name = self.image_name
args = ['inspect', image_name, '--format', 'json']
rc, image_data, err = self._run(args)
if len(image_data) > 0:
return json.loads(image_data)
else:
return None
def pull_image(self, image_name=None):
if image_name is None:
image_name = self.image_name
args = ['pull', image_name, '-q']
if self.auth_file:
args.extend(['--authfile', self.auth_file])
if self.username and self.password:
cred_string = '{user}:{password}'.format(user=self.username, password=self.password)
args.extend(['--creds', cred_string])
if self.validate_certs:
args.append('--tls-verify')
if self.ca_cert_dir:
args.extend(['--cert-dir', self.ca_cert_dir])
rc, out, err = self._run(args, ignore_errors=True)
if rc != 0:
self.module.fail_json(msg='Failed to pull image {image_name}'.format(image_name=image_name))
return self.inspect_image(out.strip())
def build_image(self):
args = ['build', '-q']
args.extend(['-t', self.image_name])
if self.validate_certs:
args.append('--tls-verify')
annotation = self.build.get('annotation')
if annotation:
for k, v in annotation.items():
args.extend(['--annotation', '{k}={v}'.format(k=k, v=v)])
if self.ca_cert_dir:
args.extend(['--cert-dir', self.ca_cert_dir])
if self.build.get('force_rm'):
args.append('--force-rm')
image_format = self.build.get('format')
if image_format:
args.extend(['--format', image_format])
if not self.build.get('cache'):
args.append('--no-cache')
if self.build.get('rm'):
args.append('--rm')
volume = self.build.get('volume')
if volume:
for v in volume:
args.extend(['--volume', v])
if self.auth_file:
args.extend(['--authfile', self.auth_file])
if self.username and self.password:
cred_string = '{user}:{password}'.format(user=self.username, password=self.password)
args.extend(['--creds', cred_string])
args.append(self.path)
rc, out, err = self._run(args, ignore_errors=True)
if rc != 0:
self.module.fail_json(msg="Failed to build image {image}: {out} {err}".format(image=self.image_name, out=out, err=err))
last_id = self._get_id_from_output(out, startswith='-->')
return self.inspect_image(last_id)
def push_image(self):
args = ['push']
if self.validate_certs:
args.append('--tls-verify')
if self.ca_cert_dir:
args.extend(['--cert-dir', self.ca_cert_dir])
if self.username and self.password:
cred_string = '{user}:{password}'.format(user=self.username, password=self.password)
args.extend(['--creds', cred_string])
if self.auth_file:
args.extend(['--authfile', self.auth_file])
if self.push_args.get('compress'):
args.append('--compress')
push_format = self.push_args.get('format')
if push_format:
args.extend(['--format', push_format])
if self.push_args.get('remove_signatures'):
args.append('--remove_signatures')
sign_by_key = self.push_args.get('sign_by')
if sign_by_key:
args.extend(['--sign-by', sign_by_key])
args.append(self.image_name)
# Build the destination argument
dest = self.push_args.get('dest')
dest_format_string = '{dest}/{image_name}'
regexp = re.compile(r'/{name}(:{tag})?'.format(name=self.name, tag=self.tag))
if not dest:
if '/' not in self.name:
self.module.fail_json(msg="'push_args['dest']' is required when pushing images that do not have the remote registry in the image name")
# If the push destination contains the image name and/or the tag
# remove it and warn since it's not needed.
elif regexp.search(dest):
dest = regexp.sub('', dest)
self.module.warn("Image name and tag are automatically added to push_args['dest']. Destination changed to {dest}".format(dest=dest))
if dest and dest.endswith('/'):
dest = dest[:-1]
transport = self.push_args.get('transport')
if transport:
if not dest:
self.module.fail_json("'push_args['transport'] requires 'push_args['dest'] but it was not provided.")
if transport == 'docker':
dest_format_string = '{transport}://{dest}'
elif transport == 'ostree':
dest_format_string = '{transport}:{name}@{dest}'
else:
dest_format_string = '{transport}:{dest}'
dest_string = dest_format_string.format(transport=transport, name=self.name, dest=dest, image_name=self.image_name,)
# Only append the destination argument if the image name is not a URL
if '/' not in self.name:
args.append(dest_string)
rc, out, err = self._run(args, ignore_errors=True)
if rc != 0:
self.module.fail_json(msg="Failed to push image {image_name}: {err}".format(image_name=self.image_name, err=err))
last_id = self._get_id_from_output(
out + err, contains=':', split_on=':')
return self.inspect_image(last_id)
def remove_image(self, image_name=None):
if image_name is None:
image_name = self.image_name
args = ['rmi', image_name]
if self.force:
args.append('--force')
rc, out, err = self._run(args, ignore_errors=True)
if rc != 0:
self.module.fail_json(msg='Failed to remove image {image_name}. {err}'.format(image_name=image_name, err=err))
return out
def parse_repository_tag(repo_name):
parts = repo_name.rsplit('@', 1)
if len(parts) == 2:
return tuple(parts)
parts = repo_name.rsplit(':', 1)
if len(parts) == 2 and '/' not in parts[1]:
return tuple(parts)
return repo_name, None
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True),
tag=dict(type='str', default='latest'),
pull=dict(type='bool', default=True),
push=dict(type='bool', default=False),
path=dict(type='str'),
force=dict(type='bool', default=False),
state=dict(type='str', default='present', choices=['absent', 'present', 'build']),
validate_certs=dict(type='bool', default=True, aliases=['tlsverify', 'tls_verify']),
executable=dict(type='str', default='podman'),
auth_file=dict(type='path', aliases=['authfile']),
username=dict(type='str'),
password=dict(type='str', no_log=True),
ca_cert_dir=dict(type='path'),
build=dict(
type='dict',
aliases=['build_args', 'buildargs'],
default={},
options=dict(
annotation=dict(type='dict'),
force_rm=dict(type='bool'),
format=dict(
type='str',
choices=['oci', 'docker'],
default='oci'
),
cache=dict(type='bool', default=True),
rm=dict(type='bool', default=True),
volume=dict(type='list'),
),
),
push_args=dict(
type='dict',
default={},
options=dict(
compress=dict(type='bool'),
format=dict(type='str', choices=['oci', 'v2s1', 'v2s2']),
remove_signatures=dict(type='bool'),
sign_by=dict(type='str'),
dest=dict(type='str', aliases=['destination'],),
transport=dict(
type='str',
choices=[
'dir',
'docker-archive',
'docker-daemon',
'oci-archive',
'ostree',
]
),
),
),
),
supports_check_mode=True,
required_together=(
['username', 'password'],
),
mutually_exclusive=(
['authfile', 'username'],
['authfile', 'password'],
),
)
results = dict(
changed=False,
actions=[],
image={},
)
PodmanImageManager(module, results)
module.exit_json(**results)
if __name__ == '__main__':
main()

View file

@ -1,239 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
module: podman_image_info
author:
- Sam Doran (@samdoran)
version_added: '2.8'
short_description: Gather info about images using podman
notes:
- Podman may required elevated privileges in order to run properly.
description:
- Gather info about images using C(podman)
options:
executable:
description:
- Path to C(podman) executable if it is not in the C($PATH) on the machine running C(podman)
default: 'podman'
type: str
name:
description:
- List of tags or UID to gather info about. If no name is given return info about all images.
"""
EXAMPLES = """
- name: Gather info for all images
podman_image_info:
- name: Gather info on a specific image
podman_image_info:
name: nginx
- name: Gather info on several images
podman_image_info:
name:
- redis
- quay.io/bitnami/wildfly
"""
RETURN = """
images:
description: info from all or specified images
returned: always
type: dict
sample: [
{
"Annotations": {},
"Architecture": "amd64",
"Author": "",
"Comment": "from Bitnami with love",
"ContainerConfig": {
"Cmd": [
"nami",
"start",
"--foreground",
"wildfly"
],
"Entrypoint": [
"/app-entrypoint.sh"
],
"Env": [
"PATH=/opt/bitnami/java/bin:/opt/bitnami/wildfly/bin:/opt/bitnami/nami/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"IMAGE_OS=debian-9",
"NAMI_VERSION=0.0.9-0",
"GPG_KEY_SERVERS_LIST=ha.pool.sks-keyservers.net \
hkp://p80.pool.sks-keyservers.net:80 keyserver.ubuntu.com hkp://keyserver.ubuntu.com:80 pgp.mit.edu",
"TINI_VERSION=v0.13.2",
"TINI_GPG_KEY=595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7",
"GOSU_VERSION=1.10",
"GOSU_GPG_KEY=B42F6819007F00F88E364FD4036A9C25BF357DD4",
"BITNAMI_IMAGE_VERSION=14.0.1-debian-9-r12",
"BITNAMI_APP_NAME=wildfly",
"WILDFLY_JAVA_HOME=",
"WILDFLY_JAVA_OPTS=",
"WILDFLY_MANAGEMENT_HTTP_PORT_NUMBER=9990",
"WILDFLY_PASSWORD=bitnami",
"WILDFLY_PUBLIC_CONSOLE=true",
"WILDFLY_SERVER_AJP_PORT_NUMBER=8009",
"WILDFLY_SERVER_HTTP_PORT_NUMBER=8080",
"WILDFLY_SERVER_INTERFACE=0.0.0.0",
"WILDFLY_USERNAME=user",
"WILDFLY_WILDFLY_HOME=/home/wildfly",
"WILDFLY_WILDFLY_OPTS=-Dwildfly.as.deployment.ondemand=false"
],
"ExposedPorts": {
"8080/tcp": {},
"9990/tcp": {}
},
"Labels": {
"maintainer": "Bitnami <containers@bitnami.com>"
}
},
"Created": "2018-09-25T04:07:45.934395523Z",
"Digest": "sha256:5c7d8e2dd66dcf4a152a4032a1d3c5a33458c67e1c1335edd8d18d738892356b",
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/containers/storage/overlay/a9dbf5616cc16919a8ac0dfc60aff87a72b5be52994c4649fcc91a089a12931\
f/diff:/var/lib/containers/storage/overlay/67129bd46022122a7d8b7acb490092af6c7ce244ce4fbd7d9e2d2b7f5979e090/diff:/var/lib/containers/storage/overlay/7c51242c\
4c5db5c74afda76d7fdbeab6965d8b21804bb3fc597dee09c770b0ca/diff:/var/lib/containers/storage/overlay/f97315dc58a9c002ba0cabccb9933d4b0d2113733d204188c88d72f75569b57b/diff:/var/lib/containers/storage/overlay/1dbde2dd497ddde2b467727125b900958a051a72561e58d29abe3d660dcaa9a7/diff:/var/lib/containers/storage/overlay/4aad9d80f30c3f0608f58173558b7554d84dee4dc4479672926eca29f75e6e33/diff:/var/lib/containers/storage/overlay/6751fc9b6868254870c062d75a511543fc8cfda2ce6262f4945f107449219632/diff:/var/lib/containers/storage/overlay/a27034d79081347421dd24d7e9e776c18271cd9a6e51053cb39af4d3d9c400e8/diff:/var/lib/containers/storage/overlay/537cf0045ed9cd7989f7944e7393019c81b16c1799a2198d8348cd182665397f/diff:/var/lib/containers/storage/overlay/27578615c5ae352af4e8449862d61aaf5c11b105a7d5905af55bd01b0c656d6e/diff:/var/lib/containers/storage/overlay/566542742840fe3034b3596f7cb9e62a6274c95a69f368f9e713746f8712c0b6/diff",
"MergedDir": "/var/lib/containers/storage/overlay/72bb96d6\
c53ad57a0b1e44cab226a6251598accbead40b23fac89c19ad8c25ca/merged",
"UpperDir": "/var/lib/containers/storage/overlay/72bb96d6c53ad57a0b1e44cab226a6251598accbead40b23fac89c19ad8c25ca/diff",
"WorkDir": "/var/lib/containers/storage/overlay/72bb96d6c53ad57a0b1e44cab226a6251598accbead40b23fac89c19ad8c25ca/work"
},
"Name": "overlay"
},
"Id": "bcacbdf7a119c0fa934661ca8af839e625ce6540d9ceb6827cdd389f823d49e0",
"Labels": {
"maintainer": "Bitnami <containers@bitnami.com>"
},
"ManifestType": "application/vnd.docker.distribution.manifest.v1+prettyjws",
"Os": "linux",
"Parent": "",
"RepoDigests": [
"quay.io/bitnami/wildfly@sha256:5c7d8e2dd66dcf4a152a4032a1d3c5a33458c67e1c1335edd8d18d738892356b"
],
"RepoTags": [
"quay.io/bitnami/wildfly:latest"
],
"RootFS": {
"Layers": [
"sha256:75391df2c87e076b0c2f72d20c95c57dc8be7ee684cc07273416cce622b43367",
"sha256:7dd303f041039bfe8f0833092673ac35f93137d10e0fbc4302021ea65ad57731",
"sha256:720d9edf0cd2a9bb56b88b80be9070dbfaad359514c70094c65066963fed485d",
"sha256:6a567ecbf97725501a634fcb486271999aa4591b633b4ae9932a46b40f5aaf47",
"sha256:59e9a6db8f178f3da868614564faabb2820cdfb69be32e63a4405d6f7772f68c",
"sha256:310a82ccb092cd650215ab375da8943d235a263af9a029b8ac26a281446c04db",
"sha256:36cb91cf4513543a8f0953fed785747ea18b675bc2677f3839889cfca0aac79e"
],
"Type": "layers"
},
"Size": 569919342,
"User": "",
"Version": "17.06.0-ce",
"VirtualSize": 569919342
}
]
"""
import json
from ansible.module_utils.basic import AnsibleModule
def image_exists(module, executable, name):
command = [executable, 'image', 'exists', name]
rc, out, err = module.run_command(command)
if rc == 1:
return False
elif 'Command "exists" not found' in err:
# The 'exists' test is available in podman >= 0.12.1
command = [executable, 'image', 'ls', '-q', name]
rc2, out2, err2 = module.run_command(command)
if rc2 != 0:
return False
return True
def filter_invalid_names(module, executable, name):
valid_names = []
names = name
if not isinstance(name, list):
names = [name]
for name in names:
if image_exists(module, executable, name):
valid_names.append(name)
return valid_names
def get_image_info(module, executable, name):
names = name
if not isinstance(name, list):
names = [name]
if len(names) > 0:
command = [executable, 'image', 'inspect']
command.extend(names)
rc, out, err = module.run_command(command)
if rc != 0:
module.fail_json(msg="Unable to gather info for '{0}': {1}".format(', '.join(names), err))
return out
else:
return json.dumps([])
def get_all_image_info(module, executable):
command = [executable, 'image', 'ls', '-q']
rc, out, err = module.run_command(command)
name = out.strip().split('\n')
out = get_image_info(module, executable, name)
return out
def main():
module = AnsibleModule(
argument_spec=dict(
executable=dict(type='str', default='podman'),
name=dict(type='list')
),
supports_check_mode=True,
)
executable = module.params['executable']
name = module.params.get('name')
executable = module.get_bin_path(executable, required=True)
if name:
valid_names = filter_invalid_names(module, executable, name)
results = json.loads(get_image_info(module, executable, valid_names))
else:
results = json.loads(get_all_image_info(module, executable))
results = dict(
changed=False,
images=results
)
module.exit_json(**results)
if __name__ == '__main__':
main()

View file

@ -1,105 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
module: podman_volume_info
author:
- "Sagi Shnaidman (@sshnaidm)"
version_added: '2.10'
short_description: Gather info about podman volumes
notes: []
description:
- Gather info about podman volumes with podman inspect command.
requirements:
- "Podman installed on host"
options:
name:
description:
- Name of the volume
type: str
executable:
description:
- Path to C(podman) executable if it is not in the C($PATH) on the
machine running C(podman)
default: 'podman'
type: str
"""
EXAMPLES = """
- name: Gather info about all present volumes
podman_volume_info:
- name: Gather info about specific volume
podman_volume_info:
name: specific_volume
"""
RETURN = """
volumes:
description: Facts from all or specified volumes
returned: always
type: list
sample: [
{
"name": "testvolume",
"labels": {},
"mountPoint": "/home/ansible/.local/share/testvolume/_data",
"driver": "local",
"options": {},
"scope": "local"
}
]
"""
import json
from ansible.module_utils.basic import AnsibleModule
def get_volume_info(module, executable, name):
command = [executable, 'volume', 'inspect']
if name:
command.append(name)
else:
command.append("--all")
rc, out, err = module.run_command(command)
if rc != 0 or 'no such volume' in err:
module.fail_json(msg="Unable to gather info for %s: %s" % (name or 'all volumes', err))
if not out or json.loads(out) is None:
return [], out, err
return json.loads(out), out, err
def main():
module = AnsibleModule(
argument_spec=dict(
executable=dict(type='str', default='podman'),
name=dict(type='str')
),
supports_check_mode=True,
)
name = module.params['name']
executable = module.get_bin_path(module.params['executable'], required=True)
inspect_results, out, err = get_volume_info(module, executable, name)
results = {
"changed": False,
"volumes": inspect_results,
"stderr": err
}
module.exit_json(**results)
if __name__ == '__main__':
main()

View file

@ -1,161 +0,0 @@
# Based on the docker connection plugin
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# Connection plugin for building container images using buildah tool
# https://github.com/projectatomic/buildah
#
# Written by: Tomas Tomecek (https://github.com/TomasTomecek)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
connection: buildah
short_description: Interact with an existing buildah container
description:
- Run commands or put/fetch files to an existing container using buildah tool.
author: Tomas Tomecek (ttomecek@redhat.com)
version_added: 2.4
options:
remote_addr:
description:
- The ID of the container you want to access.
default: inventory_hostname
vars:
- name: ansible_host
# keyword:
# - name: hosts
remote_user:
description:
- User specified via name or ID which is used to execute commands inside the container.
ini:
- section: defaults
key: remote_user
env:
- name: ANSIBLE_REMOTE_USER
vars:
- name: ansible_user
# keyword:
# - name: remote_user
"""
import shlex
import shutil
import subprocess
import ansible.constants as C
from ansible.module_utils._text import to_bytes, to_native
from ansible.plugins.connection import ConnectionBase, ensure_connect
from ansible.utils.display import Display
display = Display()
# this _has to be_ named Connection
class Connection(ConnectionBase):
"""
This is a connection plugin for buildah: it uses buildah binary to interact with the containers
"""
# String used to identify this Connection class from other classes
transport = 'buildah'
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
self._container_id = self._play_context.remote_addr
self._connected = False
# container filesystem will be mounted here on host
self._mount_point = None
# `buildah inspect` doesn't contain info about what the default user is -- if it's not
# set, it's empty
self.user = self._play_context.remote_user
def _set_user(self):
self._buildah(b"config", [b"--user=" + to_bytes(self.user, errors='surrogate_or_strict')])
def _buildah(self, cmd, cmd_args=None, in_data=None):
"""
run buildah executable
:param cmd: buildah's command to execute (str)
:param cmd_args: list of arguments to pass to the command (list of str/bytes)
:param in_data: data passed to buildah's stdin
:return: return code, stdout, stderr
"""
local_cmd = ['buildah', cmd, '--', self._container_id]
if cmd_args:
local_cmd += cmd_args
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
display.vvv("RUN %s" % (local_cmd,), host=self._container_id)
p = subprocess.Popen(local_cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input=in_data)
stdout = to_bytes(stdout, errors='surrogate_or_strict')
stderr = to_bytes(stderr, errors='surrogate_or_strict')
return p.returncode, stdout, stderr
def _connect(self):
"""
no persistent connection is being maintained, mount container's filesystem
so we can easily access it
"""
super(Connection, self)._connect()
rc, self._mount_point, stderr = self._buildah("mount")
self._mount_point = self._mount_point.strip()
display.vvvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr))
self._connected = True
@ensure_connect
def exec_command(self, cmd, in_data=None, sudoable=False):
""" run specified command in a running OCI container using buildah """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
# shlex.split has a bug with text strings on Python-2.6 and can only handle text strings on Python-3
cmd_args_list = shlex.split(to_native(cmd, errors='surrogate_or_strict'))
rc, stdout, stderr = self._buildah("run", cmd_args_list, in_data)
display.vvvvv("STDOUT %r STDERR %r" % (stderr, stderr))
return rc, stdout, stderr
def put_file(self, in_path, out_path):
""" Place a local file located in 'in_path' inside container at 'out_path' """
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._container_id)
real_out_path = self._mount_point + to_bytes(out_path, errors='surrogate_or_strict')
shutil.copyfile(
to_bytes(in_path, errors='surrogate_or_strict'),
to_bytes(real_out_path, errors='surrogate_or_strict')
)
# alternatively, this can be implemented using `buildah copy`:
# rc, stdout, stderr = self._buildah(
# "copy",
# [to_bytes(in_path, errors='surrogate_or_strict'),
# to_bytes(out_path, errors='surrogate_or_strict')]
# )
def fetch_file(self, in_path, out_path):
""" obtain file specified via 'in_path' from the container and place it at 'out_path' """
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._container_id)
real_in_path = self._mount_point + to_bytes(in_path, errors='surrogate_or_strict')
shutil.copyfile(
to_bytes(real_in_path, errors='surrogate_or_strict'),
to_bytes(out_path, errors='surrogate_or_strict')
)
def close(self):
""" unmount container's filesystem """
super(Connection, self).close()
rc, stdout, stderr = self._buildah("umount")
display.vvvvv("RC %s STDOUT %r STDERR %r" % (rc, stdout, stderr))
self._connected = False

View file

@ -1,208 +0,0 @@
# Based on the buildah connection plugin
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# Connection plugin to interact with existing podman containers.
# https://github.com/containers/libpod
#
# Written by: Tomas Tomecek (https://github.com/TomasTomecek)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import shlex
import shutil
import subprocess
from ansible.errors import AnsibleError
from ansible.module_utils._text import to_bytes, to_native
from ansible.plugins.connection import ConnectionBase, ensure_connect
from ansible.utils.display import Display
display = Display()
DOCUMENTATION = """
author: Tomas Tomecek (ttomecek@redhat.com)
connection: podman
short_description: Interact with an existing podman container
description:
- Run commands or put/fetch files to an existing container using podman tool.
version_added: 2.8
options:
remote_addr:
description:
- The ID of the container you want to access.
default: inventory_hostname
vars:
- name: ansible_host
remote_user:
description:
- User specified via name or UID which is used to execute commands inside the container. If you
specify the user via UID, you must set C(ANSIBLE_REMOTE_TMP) to a path that exits
inside the container and is writable by Ansible.
ini:
- section: defaults
key: remote_user
env:
- name: ANSIBLE_REMOTE_USER
vars:
- name: ansible_user
podman_extra_args:
description:
- Extra arguments to pass to the podman command line.
default: ''
ini:
- section: defaults
key: podman_extra_args
vars:
- name: ansible_podman_extra_args
env:
- name: ANSIBLE_PODMAN_EXTRA_ARGS
podman_executable:
description:
- Executable for podman command.
default: podman
vars:
- name: ansible_podman_executable
env:
- name: ANSIBLE_PODMAN_EXECUTABLE
"""
# this _has to be_ named Connection
class Connection(ConnectionBase):
"""
This is a connection plugin for podman. It uses podman binary to interact with the containers
"""
# String used to identify this Connection class from other classes
transport = 'podman'
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
self._container_id = self._play_context.remote_addr
self._connected = False
# container filesystem will be mounted here on host
self._mount_point = None
self.user = self._play_context.remote_user
def _podman(self, cmd, cmd_args=None, in_data=None, use_container_id=True):
"""
run podman executable
:param cmd: podman's command to execute (str)
:param cmd_args: list of arguments to pass to the command (list of str/bytes)
:param in_data: data passed to podman's stdin
:return: return code, stdout, stderr
"""
podman_exec = self.get_option('podman_executable')
podman_cmd = distutils.spawn.find_executable(podman_exec)
if not podman_cmd:
raise AnsibleError("%s command not found in PATH" % podman_exec)
local_cmd = [podman_cmd]
if self.get_option('podman_extra_args'):
local_cmd += shlex.split(
to_native(
self.get_option('podman_extra_args'),
errors='surrogate_or_strict'))
local_cmd.append(cmd)
if use_container_id:
local_cmd.append(self._container_id)
if cmd_args:
local_cmd += cmd_args
local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd]
display.vvv("RUN %s" % (local_cmd,), host=self._container_id)
p = subprocess.Popen(local_cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(input=in_data)
display.vvvvv("STDOUT %s" % stdout)
display.vvvvv("STDERR %s" % stderr)
display.vvvvv("RC CODE %s" % p.returncode)
stdout = to_bytes(stdout, errors='surrogate_or_strict')
stderr = to_bytes(stderr, errors='surrogate_or_strict')
return p.returncode, stdout, stderr
def _connect(self):
"""
no persistent connection is being maintained, mount container's filesystem
so we can easily access it
"""
super(Connection, self)._connect()
rc, self._mount_point, stderr = self._podman("mount")
if rc != 0:
display.v("Failed to mount container %s: %s" % (self._container_id, stderr.strip()))
else:
self._mount_point = self._mount_point.strip()
display.vvvvv("MOUNTPOINT %s RC %s STDERR %r" % (self._mount_point, rc, stderr))
self._connected = True
@ensure_connect
def exec_command(self, cmd, in_data=None, sudoable=False):
""" run specified command in a running OCI container using podman """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
# shlex.split has a bug with text strings on Python-2.6 and can only handle text strings on Python-3
cmd_args_list = shlex.split(to_native(cmd, errors='surrogate_or_strict'))
if self.user:
cmd_args_list += ["--user", self.user]
rc, stdout, stderr = self._podman("exec", cmd_args_list, in_data)
display.vvvvv("STDOUT %r STDERR %r" % (stderr, stderr))
return rc, stdout, stderr
def put_file(self, in_path, out_path):
""" Place a local file located in 'in_path' inside container at 'out_path' """
super(Connection, self).put_file(in_path, out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._container_id)
if not self._mount_point:
rc, stdout, stderr = self._podman(
"cp", [in_path, self._container_id + ":" + out_path], use_container_id=False
)
if rc != 0:
if 'cannot copy into running rootless container with pause set' in to_native(stderr):
rc, stdout, stderr = self._podman(
"cp", ["--pause=false", in_path, self._container_id + ":" + out_path], use_container_id=False
)
if rc != 0:
raise AnsibleError(
"Failed to copy file from %s to %s in container %s\n%s" % (
in_path, out_path, self._container_id, stderr)
)
else:
real_out_path = self._mount_point + to_bytes(out_path, errors='surrogate_or_strict')
shutil.copyfile(
to_bytes(in_path, errors='surrogate_or_strict'),
to_bytes(real_out_path, errors='surrogate_or_strict')
)
def fetch_file(self, in_path, out_path):
""" obtain file specified via 'in_path' from the container and place it at 'out_path' """
super(Connection, self).fetch_file(in_path, out_path)
display.vvv("FETCH %s TO %s" % (in_path, out_path), host=self._container_id)
if not self._mount_point:
rc, stdout, stderr = self._podman(
"cp", [self._container_id + ":" + in_path, out_path], use_container_id=False)
if rc != 0:
raise AnsibleError("Failed to fetch file from %s to %s from container %s\n%s" % (
in_path, out_path, self._container_id, stderr))
else:
real_in_path = self._mount_point + to_bytes(in_path, errors='surrogate_or_strict')
shutil.copyfile(
to_bytes(real_in_path, errors='surrogate_or_strict'),
to_bytes(out_path, errors='surrogate_or_strict')
)
def close(self):
""" unmount container's filesystem """
super(Connection, self).close()
# we actually don't need to unmount since the container is mounted anyway
# rc, stdout, stderr = self._podman("umount")
# display.vvvvv("RC %s STDOUT %r STDERR %r" % (rc, stdout, stderr))
self._connected = False

View file

@ -1,3 +0,0 @@
needs/root
non_local
unsupported

View file

@ -1 +0,0 @@
../connection_posix/test.sh

View file

@ -1,7 +0,0 @@
#!/usr/bin/env bash
set -eux
./posix.sh "$@"
ANSIBLE_REMOTE_USER="1000" ./posix.sh "$@"

View file

@ -1,12 +0,0 @@
[buildah]
buildah-container ansible_ssh_pipelining=true
[buildah:vars]
# 1. install buildah
# 2. create container:
# $ sudo buildah from --name=buildah-container python:2
# 3. run test:
# $ ansible-test integration connection_buildah
# 6. remove container
# $ sudo buildah rm buildah-container
ansible_host=buildah-container
ansible_connection=buildah

View file

@ -1,2 +0,0 @@
non_local
unsupported

View file

@ -1 +0,0 @@
../connection_posix/test.sh

View file

@ -1,14 +0,0 @@
#!/usr/bin/env bash
set -eux
./posix.sh "$@"
ANSIBLE_REMOTE_TMP="/tmp" ANSIBLE_REMOTE_USER="1000" ./posix.sh "$@"
ANSIBLE_PODMAN_EXECUTABLE=fakepodman ./posix.sh "$@" 2>&1 | grep "fakepodman command not found in PATH"
ANSIBLE_PODMAN_EXECUTABLE=fakepodman ./posix.sh "$@" && {
echo "Playbook with fakepodman should fail!"
exit 1
}
ANSIBLE_VERBOSITY=4 ANSIBLE_PODMAN_EXTRA_ARGS=" --log-level debug " ./posix.sh "$@" | grep "level=debug msg="

View file

@ -1,15 +0,0 @@
[podman]
podman-container
[podman:vars]
# 1. install podman
# 2. create container:
# podman pull python:3-alpine
# podman run -d --name podman-container python:3-alpine sleep 999999
# 3. run test:
# ./bin/ansible-test integration connection_podman
# 6. remove container
# podman stop podman-container
# podman rm podman-container
ansible_host=podman-container
ansible_connection=podman
ansible_python_interpreter=/usr/local/bin/python

View file

@ -1,5 +0,0 @@
shippable/posix/group2
skip/aix
skip/osx
skip/freebsd
destructive

View file

@ -1,2 +0,0 @@
dependencies:
- setup_podman

View file

@ -1,91 +0,0 @@
- name: Test podman_container_info
when:
- ansible_facts.virtualization_type != 'docker'
- ansible_facts.distribution == 'RedHat'
block:
- name: Generate random value for container name
set_fact:
container_name: "{{ 'ansible-test-podman-%0x' % ((2**32) | random) }}"
- name: Make sure container doesn't exist
command: podman container rm -f {{ container_name }}
ignore_errors: true
- name: Get missing container info
podman_container_info:
name: "{{ container_name }}"
register: nonexist
- name: Check results of missing container info
assert:
that:
- "'containers' in nonexist"
- nonexist is succeeded
- nonexist.containers == []
- name: Get missing multiple container info
podman_container_info:
name:
- "{{ container_name }}"
- neverexist
- whatever
register: nonexist2
ignore_errors: true
- name: Check results of missing multiple container info
assert:
that:
- "'containers' in nonexist2"
- nonexist2 is succeeded
- nonexist2.containers == []
- name: Make sure container exists
command: podman container run -d --name {{ container_name }} alpine sleep 15m
- name: Get existing container info
podman_container_info:
name: "{{ container_name }}"
register: existing_container
- name: Get mixed existing and non-existing container info
podman_container_info:
name:
- "{{ container_name }}"
- whatever
register: mixed_existing_container
- name: Get all containers info
podman_container_info:
register: all_containers
- name: Dump podman container inspect result
debug: var=existing_container
- name: Comparison with 'podman container inspect'
command: podman container inspect "{{ container_name }}"
register: podman_inspect
- name: Convert podman inspect output to JSON
set_fact:
podman_inspect_result: "{{ podman_inspect.stdout | from_json }}"
- name: Cleanup
command: podman container rm -f {{ container_name }}
- name: Make checks
assert:
that:
- "'containers' in existing_container"
- existing_container.containers
- "existing_container.containers == podman_inspect_result"
- all_containers.containers == existing_container.containers
- "'containers' in mixed_existing_container"
- mixed_existing_container.containers
- existing_container.containers == mixed_existing_container.containers
always:
- name: Cleanup
command: podman container rm -f {{ container_name }}
ignore_errors: true

View file

@ -1,5 +0,0 @@
shippable/posix/group3
skip/aix
skip/osx
skip/freebsd
destructive

View file

@ -1,3 +0,0 @@
FROM quay.io/coreos/alpine-sh
ENV VAR testing
WORKDIR ${VAR}

View file

@ -1,2 +0,0 @@
dependencies:
- setup_podman

View file

@ -1,144 +0,0 @@
- name: Test podman_image
when:
- ansible_facts.virtualization_type != 'docker'
- ansible_facts.distribution == 'RedHat'
block:
- name: Pull image
podman_image:
name: quay.io/coreos/alpine-sh
register: pull1
- name: Pull image again
podman_image:
name: quay.io/coreos/alpine-sh
register: pull2
- name: List images
command: podman image ls
register: images
- name: Ensure image was pulled properly
assert:
that:
- pull1 is changed
- pull2 is not changed
- "'alpine-sh' in images.stdout"
- name: Remove image
podman_image:
name: quay.io/coreos/alpine-sh
state: absent
register: rmi1
- name: Remove image again
podman_image:
name: quay.io/coreos/alpine-sh
state: absent
register: rmi2
- name: List images
command: podman image ls
register: images
- name: Ensure image was removed properly
assert:
that:
- rmi1 is changed
- rmi2 is not changed
- "'alpine-sh' not in images.stdout"
- name: Pull a specific version of an image
podman_image:
name: quay.io/coreos/etcd
tag: v3.3.11
register: specific_image1
- name: Pull a specific version of an image again
podman_image:
name: quay.io/coreos/etcd
tag: v3.3.11
register: specific_image2
- name: List images
command: podman image ls
register: images
- name: Ensure specific image was pulled properly
assert:
that:
- specific_image1 is changed
- specific_image2 is not changed
- "'v3.3.11' in images.stdout"
- name: Create a build dir
file:
path: /var/tmp/build
state: directory
- name: Copy Containerfile
copy:
src: Containerfile
dest: /var/tmp/build/Dockerfile
- name: Build OCI image
podman_image:
name: testimage
path: /var/tmp/build
register: oci_build1
- name: Build OCI image again
podman_image:
name: testimage
path: /var/tmp/build
register: oci_build2
- name: Inspect build image
podman_image_info:
name: testimage
register: testimage_info
- name: Ensure OCI image was built properly
assert:
that:
- oci_build1 is changed
- oci_build2 is not changed
- "'localhost/testimage:latest' in testimage_info.images[0]['RepoTags'][0]"
- name: Build Docker image
podman_image:
name: dockerimage
path: /var/tmp/build
build:
format: docker
register: docker_build1
- name: Build Docker image again
podman_image:
name: dockerimage
path: /var/tmp/build
build:
format: docker
register: docker_build2
- name: Inspect build image
podman_image_info:
name: dockerimage
register: dockerimage_info
- name: Ensure Docker image was built properly
assert:
that:
- docker_build1 is changed
- docker_build2 is not changed
- "'localhost/dockerimage:latest' in dockerimage_info.images[0]['RepoTags'][0]"
always:
- name: Cleanup images
podman_image:
name: "{{ item }}"
state: absent
loop:
- quay.io/coreos/alpine-sh
- quay.io/coreos/etcd:v3.3.11
- localhost/testimage
- localhost/dockerimage

View file

@ -1,5 +0,0 @@
shippable/posix/group2
skip/aix
skip/osx
skip/freebsd
destructive

View file

@ -1,2 +0,0 @@
dependencies:
- setup_podman

View file

@ -1,53 +0,0 @@
- name: Test podman_image_info
when:
- ansible_facts.virtualization_type != 'docker'
- ansible_facts.distribution == 'RedHat'
block:
- name: Pull image
command: podman pull quay.io/coreos/etcd
- name: Get info on all images
podman_image_info:
register: all_image_result
- name: Pull another image
command: podman pull quay.io/coreos/dnsmasq
- name: Get info on specific image
podman_image_info:
name: dnsmasq
register: named_image_result
- name:
assert:
that:
- all_image_result.images | length > 0
- named_image_result.images | length == 1
- "'dnsmasq' in named_image_result.images[0]['RepoTags'][0]"
- name: Get info on single image that does not exist
podman_image_info:
name: nope
register: single_nonexistant
- name: Get info on multiple images that do not exist
podman_image_info:
name:
- nope
- reallynope
register: multiple_nonexistant
- name: Get info with one image that does not exist
podman_image_info:
name:
- dnsmasq
- nope
- etcd
register: mixed_nonexistant
- name: Ensure image info was returned when non-existant image info was requisted
assert:
that:
- single_nonexistant.images | length == 0
- multiple_nonexistant.images | length == 0
- mixed_nonexistant.images | length == 2

View file

@ -1,5 +0,0 @@
shippable/posix/group2
skip/aix
skip/osx
skip/freebsd
destructive

View file

@ -1,2 +0,0 @@
dependencies:
- setup_podman

View file

@ -1,62 +0,0 @@
- name: Test podman_volume_info
when:
- ansible_facts.virtualization_type != 'docker'
- ansible_facts.distribution == 'RedHat'
block:
- name: Print podman version
command: podman version
- name: Generate random value for volume name
set_fact:
volume_name: "{{ 'ansible-test-podman-%0x' % ((2**32) | random) }}"
- name: Make sure volume doesn't exist
command: podman volume rm {{ volume_name }}
ignore_errors: true
- name: Get missing volume info
podman_volume_info:
name: "{{ volume_name }}"
register: nonexist
ignore_errors: true
- name: Check results
assert:
that:
- "'volumes' not in nonexist"
- nonexist is failed
- name: Make sure volume exists
command: podman volume create {{ volume_name }}
- name: Get existing volume info
podman_volume_info:
name: "{{ volume_name }}"
register: existing_volume
- name: Dump podman volume inspect result
debug: var=existing_volume
- name: Comparison with 'podman volume inspect'
command: podman volume inspect "{{ volume_name }}"
register: podman_inspect
- name: Convert podman inspect output to JSON
set_fact:
podman_inspect_result: "{{ podman_inspect.stdout | from_json }}"
- name: Cleanup
command: podman volume rm {{ volume_name }}
- name: Make checks
assert:
that:
- "'volumes' in existing_volume"
- existing_volume.volumes
- "existing_volume.volumes == podman_inspect_result"
always:
- name: Cleanup
command: podman volume rm {{ volume_name }}
ignore_errors: true

View file

@ -1 +0,0 @@
podman_package: podman-1.4.*

View file

@ -1,9 +0,0 @@
- name: remove podman packages
yum:
name: 'podman*'
state: absent
listen: cleanup podman
- name: remove extras repo
command: "{{ repo_command[ansible_facts.distribution ~ ansible_facts.distribution_major_version]['disable'] | default('echo') }}"
listen: cleanup podman

View file

@ -1,19 +0,0 @@
- block:
- name: Enable extras repo
command: "{{ repo_command[ansible_facts.distribution ~ ansible_facts.distribution_major_version]['enable'] | default('echo') }}"
notify: cleanup podman
- name: Install podman
yum:
name: "{{ podman_package }}"
state: present
when: ansible_facts.pkg_mgr in ['yum', 'dnf']
notify: cleanup podman
- name: Get podman version
command: podman --version
when:
- ansible_facts.distribution == 'RedHat'
- ansible_facts.virtualization_type != 'docker'
- ansible_facts.distribution_major_version is version_compare('7', '>=')

View file

@ -1,4 +0,0 @@
repo_command:
RedHat7:
enable: yum-config-manager --enable rhui-REGION-rhel-server-extras
disable: yum-config-manager --disable rhui-REGION-rhel-server-extras

View file

@ -2305,13 +2305,6 @@ lib/ansible/modules/cloud/packet/packet_sshkey.py validate-modules:parameter-typ
lib/ansible/modules/cloud/packet/packet_sshkey.py validate-modules:undocumented-parameter
lib/ansible/modules/cloud/packet/packet_volume_attachment.py pylint:ansible-bad-function
lib/ansible/modules/cloud/packet/packet_volume_attachment.py validate-modules:doc-required-mismatch
lib/ansible/modules/cloud/podman/podman_image.py validate-modules:doc-type-does-not-match-spec
lib/ansible/modules/cloud/podman/podman_image.py validate-modules:mutually_exclusive-unknown
lib/ansible/modules/cloud/podman/podman_image.py validate-modules:parameter-list-no-elements
lib/ansible/modules/cloud/podman/podman_image.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/cloud/podman/podman_image.py validate-modules:undocumented-parameter
lib/ansible/modules/cloud/podman/podman_image_info.py validate-modules:parameter-list-no-elements
lib/ansible/modules/cloud/podman/podman_image_info.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/cloud/profitbricks/profitbricks.py validate-modules:doc-choices-do-not-match-spec
lib/ansible/modules/cloud/profitbricks/profitbricks.py validate-modules:doc-default-does-not-match-spec
lib/ansible/modules/cloud/profitbricks/profitbricks.py validate-modules:doc-missing-type