Repository: ansible/molecule

Issue:
Buildah/Podman/CRI-O Virtualization Driver
# Issue Type

- Feature request

# Molecule and Ansible details

Ansible 2.7
Molecule 2.19

Molecule installation method (one of):

- pip

Ansible installation method (one of):

- OS package

# Desired Behavior

Similar to how the docker driver is setup for creating the virtualized environment using containers, Buildah (or even possibly Podman) support could provide the same functionality without the need of root privileges or the docker daemon via the use of CRI-O.

```
$ molecule init role --role-name example --driver-name buildah
```

https://docs.ansible.com/ansible/2.7/plugins/connection/buildah.html



Discussion:
cc @TomasTomecek
@ekultails seek for ideas @ https://github.com/TomasTomecek/ansible-bender :)
Related: https://github.com/ansible/ansible/pull/47519
Hello I am looking to work into this, is someone already doing it ? 
@qinqon probably not. Feel free to take a crack on it :)
Anyone started working on this?

This would be highly appreciated!
Based on some talks in the TripleO community, the CRI-O virtualization driver would actually probably use `podman` instead of `buildah`. Both utilize CRI-O instead of docker. The current road block is a wait on a few more Ansible modules to be finished/polished to better support management operations for podman containers.
When implementing this we may want to consider a fallback mecanisms regarding which container virtualization engine to be used. It would be very useful to be able to tell molecule to "use podman if available but fallback to docker if not", especially as availability varies a lot across various platforms.

As far as I know, nobody is working in adding this now which means that we would welcome any help towards this direction.

Resolving patch:
diff --git a/molecule/config.py b/molecule/config.py
--- a/molecule/config.py
+++ b/molecule/config.py
@@ -43,6 +43,7 @@
 from molecule.driver import lxc
 from molecule.driver import lxd
 from molecule.driver import openstack
+from molecule.driver import podman
 from molecule.driver import vagrant
 from molecule.lint import yamllint
 from molecule.model import schema_v2
@@ -178,6 +179,8 @@ def driver(self):
             driver = lxd.LXD(self)
         elif driver_name == 'openstack':
             driver = openstack.Openstack(self)
+        elif driver_name == 'podman':
+            driver = podman.Podman(self)
         elif driver_name == 'vagrant':
             driver = vagrant.Vagrant(self)
 
@@ -508,6 +511,7 @@ def molecule_drivers():
         lxc.LXC(None).name,
         lxd.LXD(None).name,
         openstack.Openstack(None).name,
+        podman.Podman(None).name,
         vagrant.Vagrant(None).name,
     ]
 
diff --git a/molecule/driver/podman.py b/molecule/driver/podman.py
new file mode 100644
--- /dev/null
+++ b/molecule/driver/podman.py
@@ -0,0 +1,190 @@
+#  Copyright (c) 2015-2018 Cisco Systems, Inc.
+#
+#  Permission is hereby granted, free of charge, to any person obtaining a copy
+#  of this software and associated documentation files (the "Software"), to
+#  deal in the Software without restriction, including without limitation the
+#  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+#  sell copies of the Software, and to permit persons to whom the Software is
+#  furnished to do so, subject to the following conditions:
+#
+#  The above copyright notice and this permission notice shall be included in
+#  all copies or substantial portions of the Software.
+#
+#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+#  DEALINGS IN THE SOFTWARE.
+
+from __future__ import absolute_import
+
+import os
+
+from molecule import logger
+from molecule.driver import base
+
+log = logger.get_logger(__name__)
+
+
+class Podman(base.Base):
+    """
+    The class responsible for managing `Podman`_ containers.  `Podman`_ is
+    not default driver used in Molecule.
+
+    Molecule uses Podman ansible connector and podman CLI while mapping
+    variables from ``molecule.yml`` into ``create.yml`` and ``destroy.yml``.
+
+    .. _`podman connection`: https://docs.ansible.com/ansible/latest/plugins/connection/podman.html
+
+    .. code-block:: yaml
+
+        driver:
+          name: podman
+        platforms:
+          - name: instance
+            hostname: instance
+            image: image_name:tag
+            dockerfile: Dockerfile.j2
+            pull: True|False
+            pre_build_image: True|False
+            registry:
+              url: registry.example.com
+              credentials:
+                username: $USERNAME
+                password: $PASSWORD
+            override_command: True|False
+            command: sleep infinity
+            tty: True|False
+            pid_mode: host
+            privileged: True|False
+            security_opts:
+              - seccomp=unconfined
+            volumes:
+              - /sys/fs/cgroup:/sys/fs/cgroup:ro
+            tmpfs:
+              - /tmp
+              - /run
+            capabilities:
+              - SYS_ADMIN
+            exposed_ports:
+              - 53/udp
+              - 53/tcp
+            published_ports:
+              - 0.0.0.0:8053:53/udp
+              - 0.0.0.0:8053:53/tcp
+            ulimits:
+              - nofile=1024:1028
+            dns_servers:
+              - 8.8.8.8
+            network: host
+            etc_hosts: {'host1.example.com': '10.3.1.5'}
+            cert_path: /foo/bar/cert.pem
+            tls_verify: true
+            env:
+              FOO: bar
+            restart_policy: on-failure
+            restart_retries: 1
+            buildargs:
+              http_proxy: http://proxy.example.com:8080/
+
+    If specifying the `CMD`_ directive in your ``Dockerfile.j2`` or consuming a
+    built image which declares a ``CMD`` directive, then you must set
+    ``override_command: False``. Otherwise, Molecule takes care to honour the
+    value of the ``command`` key or uses the default of ``bash -c "while true;
+    do sleep 10000; done"`` to run the container until it is provisioned.
+
+    When attempting to utilize a container image with `systemd`_ as your init
+    system inside the container to simulate a real machine, make sure to set
+    the ``privileged``, ``volume_mounts``, ``command``, and ``environment``
+    values. An example using the ``centos:7`` image is below:
+
+    .. note:: Do note that running containers in privileged mode is considerably
+              less secure.
+
+    .. code-block:: yaml
+
+        platforms:
+        - name: instance
+          image: centos:7
+          privileged: true
+          volumes:
+            - "/sys/fs/cgroup:/sys/fs/cgroup:rw"
+          command: "/usr/sbin/init"
+          tty: True
+
+    .. code-block:: bash
+
+        $ pip install molecule[podman]
+
+    When pulling from a private registry, it is the user's discretion to decide
+    whether to use hard-code strings or environment variables for passing
+    credentials to molecule.
+
+    .. important::
+
+        Hard-coded credentials in ``molecule.yml`` should be avoided, instead use
+        `variable substitution`_.
+
+    Provide a list of files Molecule will preserve, relative to the scenario
+    ephemeral directory, after any ``destroy`` subcommand execution.
+
+    .. code-block:: yaml
+
+        driver:
+          name: podman
+          safe_files:
+            - foo
+
+    .. _`Podman`: https://podman.io/
+    .. _`systemd`: https://www.freedesktop.org/wiki/Software/systemd/
+    .. _`CMD`: https://docs.docker.com/engine/reference/builder/#cmd
+    """  # noqa
+
+    def __init__(self, config):
+        super(Podman, self).__init__(config)
+        self._name = 'podman'
+
+    @property
+    def name(self):
+        return self._name
+
+    @name.setter
+    def name(self, value):
+        self._name = value
+
+    @property
+    def login_cmd_template(self):
+        return ('podman exec '
+                '-e COLUMNS={columns} '
+                '-e LINES={lines} '
+                '-e TERM=bash '
+                '-e TERM=xterm '
+                '-ti {instance} bash')
+
+    @property
+    def default_safe_files(self):
+        return [
+            os.path.join(self._config.scenario.ephemeral_directory,
+                         'Dockerfile')
+        ]
+
+    @property
+    def default_ssh_connection_options(self):
+        return []
+
+    def login_options(self, instance_name):
+        return {'instance': instance_name}
+
+    def ansible_connection_options(self, instance_name):
+        return {'ansible_connection': 'podman'}
+
+    def sanity_checks(self):
+        """Implement Podman driver sanity checks."""
+
+        if self._config.state.sanity_checked:
+            return
+
+        log.info("Sanity checks: '{}'".format(self._name))
+        self._config.state.change_state('sanity_checked', True)
diff --git a/molecule/model/schema_v2.py b/molecule/model/schema_v2.py
--- a/molecule/model/schema_v2.py
+++ b/molecule/model/schema_v2.py
@@ -70,6 +70,7 @@ def pre_validate_base_schema(env, keep_string):
                         'lxc',
                         'lxd',
                         'openstack',
+                        'podman',
                         'vagrant',
                     ],
                     # NOTE(retr0h): Some users use an environment variable to
@@ -774,6 +775,149 @@ def pre_validate_base_schema(env, keep_string):
     },
 }
 
+platforms_podman_schema = {
+    'platforms': {
+        'type': 'list',
+        'schema': {
+            'type': 'dict',
+            'schema': {
+                'name': {
+                    'type': 'string',
+                },
+                'hostname': {
+                    'type': 'string',
+                },
+                'image': {
+                    'type': 'string',
+                },
+                'dockerfile': {
+                    'type': 'string',
+                },
+                'pull': {
+                    'type': 'boolean',
+                },
+                'pre_build_image': {
+                    'type': 'boolean',
+                },
+                'registry': {
+                    'type': 'dict',
+                    'schema': {
+                        'url': {
+                            'type': 'string',
+                        },
+                        'credentials': {
+                            'type': 'dict',
+                            'schema': {
+                                'username': {
+                                    'type': 'string',
+                                },
+                                'password': {
+                                    'type': 'string',
+                                },
+                            }
+                        },
+                    }
+                },
+                'override_command': {
+                    'type': 'boolean',
+                    'nullable': True,
+                },
+                'command': {
+                    'type': 'string',
+                    'nullable': True,
+                },
+                'tty': {
+                    'type': 'boolean',
+                    'nullable': True,
+                },
+                'pid_mode': {
+                    'type': 'string',
+                },
+                'privileged': {
+                    'type': 'boolean',
+                },
+                'security_opts': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'volumes': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'tmpfs': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'capabilities': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'exposed_ports': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                        'coerce': 'exposed_ports'
+                    }
+                },
+                'published_ports': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'ulimits': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'dns_servers': {
+                    'type': 'list',
+                    'schema': {
+                        'type': 'string',
+                    }
+                },
+                'etc_hosts': {
+                    'type': ['string', 'dict'],
+                    'keyschema': {
+                        'type': 'string',
+                    }
+                },
+                'env': {
+                    'type': 'dict',
+                    'keysrules': {
+                        'type': 'string',
+                        'regex': '^[a-zA-Z0-9_-]+$',
+                    }
+                },
+                'restart_policy': {
+                    'type': 'string',
+                },
+                'restart_retries': {
+                    'type': 'integer',
+                },
+                'network': {
+                    'type': 'string',
+                },
+                'cert_path': {
+                    'type': 'string',
+                },
+                'tls_verify': {
+                    'type': 'boolean',
+                }
+            }
+        }
+    },
+}
+
 platforms_lxd_schema = {
     'platforms': {
         'type': 'list',
@@ -1079,6 +1223,8 @@ def validate(c):
     # Driver
     if c['driver']['name'] == 'docker':
         util.merge_dicts(schema, platforms_docker_schema)
+    elif c['driver']['name'] == 'podman':
+        util.merge_dicts(schema, platforms_podman_schema)
     elif c['driver']['name'] == 'vagrant':
         util.merge_dicts(schema, driver_vagrant_provider_section_schema)
         util.merge_dicts(schema, platforms_vagrant_schema)


Test patch:
diff --git a/test/unit/test_config.py b/test/unit/test_config.py
--- a/test/unit/test_config.py
+++ b/test/unit/test_config.py
@@ -297,6 +297,7 @@ def test_drivers_property(config_instance):
         'lxc',
         'lxd',
         'openstack',
+        'podman',
         'vagrant',
     ]
 
@@ -566,6 +567,7 @@ def test_molecule_drivers():
         'lxc',
         'lxd',
         'openstack',
+        'podman',
         'vagrant',
     ]