diff --git a/src/pyinfra/operations/docker.py b/src/pyinfra/operations/docker.py index d78b4f5a5..b79c41bce 100644 --- a/src/pyinfra/operations/docker.py +++ b/src/pyinfra/operations/docker.py @@ -36,6 +36,7 @@ def container( restart_policy: str | None = None, auto_remove: bool = False, dns: list[str] | None = None, + command: str | None = None, ): """ Manage Docker containers @@ -55,6 +56,7 @@ def container( + restart_policy: restart policy to apply when a container exits + auto_remove: automatically remove the container and its associated anonymous volumes when it exits + dns: list of dns servers to be used by the container + + command: custom command to run on container start **Examples:** @@ -89,6 +91,14 @@ def container( container="nginx", start=True, ) + + # Run a custom command on container start + # Note: you can omit the shell (sh -c) to use the default shell of the container + docker.container( + name="Run a custom command", + container="alpine", + command="sh -c 'echo Whatever you want'", + ) """ want_spec = ContainerSpec( @@ -103,6 +113,7 @@ def container( restart_policy, auto_remove, dns or list(), + command, ) existent_container = host.get_fact(DockerContainer, object_id=container) diff --git a/src/pyinfra/operations/util/docker.py b/src/pyinfra/operations/util/docker.py index 43836867c..bccedca67 100644 --- a/src/pyinfra/operations/util/docker.py +++ b/src/pyinfra/operations/util/docker.py @@ -169,6 +169,7 @@ class ContainerSpec: restart_policy: str | None = None auto_remove: bool = False dns: list[str] = field(default_factory=list) + command: str | None = None def container_create_args(self): args = [] @@ -203,6 +204,8 @@ def container_create_args(self): args.append("--dns {0}".format(dns)) args.append(self.image) + if self.command: + args.append(self.command) return args diff --git a/tests/operations/docker.container/add_container_with_command.json b/tests/operations/docker.container/add_container_with_command.json new file mode 100644 index 000000000..d99d02ed8 --- /dev/null +++ b/tests/operations/docker.container/add_container_with_command.json @@ -0,0 +1,17 @@ +{ + "kwargs": { + "container": "nginx", + "image": "nginx:alpine", + "present": "true", + "start": false, + "command": "sh -c 'echo leroy jenkins'" + }, + "facts": { + "docker.DockerContainer": { + "object_id=nginx": [] + } + }, + "commands": [ + "docker container create --name nginx nginx:alpine sh -c 'echo leroy jenkins'" + ] +}