liab-deployments/liab_deployments/operations/podman.py

78 lines
2 KiB
Python

from pyinfra import host
from pyinfra.api import (
FactBase,
operation,
)
from pyinfra.operations import (
server,
)
class PodmanLocalImageRepoDigests(FactBase):
"""Report the digests of a locally available container image."""
def requires_command(self, **kwargs) -> str:
return 'podman'
def command(self, tag: str):
return (
# podman doesn't like running outside $HOME
'cd && podman image inspect --format'
" '{{range .RepoDigests}}{{println .}}{{end}}'"
f' {tag} 2>/dev/null || echo MISSING'
)
def default(self):
return None
def process(self, lines):
if not lines or lines == ['MISSING']:
return None
return [
# reports with {tag}@ prefix
line.split('@', maxsplit=1)[1].strip()
for line in lines
if line.strip()
]
class SkopeoRemoteImageDigest(FactBase):
"""Report the digest of a remote container image via skopeo."""
def requires_command(self, **kwargs) -> str:
return 'skopeo'
def command(self, tag: str):
return (
f'timeout 60 skopeo inspect --format "{{{{.Digest}}}}" '
f'docker://{tag} 2>/dev/null || echo UNKNOWN'
)
def default(self):
return None
def process(self, lines):
if not lines:
return None
return lines[0].strip()
@operation()
def pull(tag: str):
local_digests = host.get_fact(PodmanLocalImageRepoDigests, tag)
remote_digest = host.get_fact(SkopeoRemoteImageDigest, tag)
image_update = (
local_digests is None
or (
remote_digest not in (None, 'UNKNOWN')
and remote_digest not in local_digests
)
)
if not image_update:
return
yield from server.shell._inner(
# need to `cd` to be in the target user's HOME,
# podman doesn't like being in the controlling user's HOME
f'cd && podman pull "{tag}"',
)