commit ec0fca16470a09e2468dabc4285813627839b1dc Author: Julien Palard Date: Thu Oct 22 15:21:45 2020 +0200 Initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4343c4d --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2020, meltygroup + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fecc5f5 --- /dev/null +++ b/README.md @@ -0,0 +1,75 @@ +# ansible-parallel + +TL;DR: + +```bash +pip install ansible-parallel +ansible-parallel *.yml +``` + +Executes multiple ansible playbooks in parallel. + +For my usage, running sequentially (using a `site.yml` containing +multiple `import_playbook`) takes 30mn, running in parallel takes +10mn. + + +## Usage + +`ansible-parallel` runs like `ansible-playbook` but accepts multiple +playbooks. All remaining options are passed to `ansible-playbook` so +feel free to run `ansible-parallel --check *.yml` for example. + + +## Example + +```bash +$ ansible-parallel *.yml +# Playbook playbook-webs.yml, ran in 123s + +web1.meltygroup.com : ok=51 changed=0 unreachable=0 failed=0 skipped=12 rescued=0 ignored=0 +web2.meltygroup.com : ok=51 changed=0 unreachable=0 failed=0 skipped=12 rescued=0 ignored=0 +web3.meltygroup.com : ok=51 changed=0 unreachable=0 failed=0 skipped=12 rescued=0 ignored=0 + + +# Playbook playbook-staging.yml, ran in 138s + +staging1.meltygroup.com : ok=64 changed=6 unreachable=0 failed=0 skipped=18 rescued=0 ignored=0 + + +# Playbook playbook-gitlab.yml, ran in 179s + +gitlab-runner1.meltygroup.com : ok=47 changed=0 unreachable=0 failed=0 skipped=13 rescued=0 ignored=0 +gitlab-runner2.meltygroup.com : ok=47 changed=0 unreachable=0 failed=0 skipped=13 rescued=0 ignored=0 +gitlab-runner3.meltygroup.com : ok=47 changed=0 unreachable=0 failed=0 skipped=13 rescued=0 ignored=0 +gitlab.meltygroup.com : ok=51 changed=0 unreachable=0 failed=0 skipped=12 rescued=0 ignored=0 + + +# Playbook playbook-devs.yml, ran in 213s + +dev1.meltygroup.com : ok=121 changed=0 unreachable=0 failed=0 skipped=22 rescued=0 ignored=0 +dev2.meltygroup.com : ok=121 changed=0 unreachable=0 failed=0 skipped=22 rescued=0 ignored=0 +``` + + +## Known alternatives + +### ansible-pull + +ansible-parallel is only good if you want to keep the push behavior of +Ansible, but if you're here you may have a lot of playbooks, and +switching to +[ansible-pull](https://docs.ansible.com/ansible/latest/cli/ansible-pull.html) +with a proper reporting system like +[ARA](https://github.com/ansible-community/ara) + + +### xargs + +A quick and dirty way of doing it in 3 lines of bash: + +``` +ls -1 *.yml | xargs -n1 -P16 sh -c 'ansible-playbook "$$0" > "$$0.log"' ||: +grep -B1 "^\(changed\|fatal\|failed\):" *.log +echo *.yml.log | xargs -n1 sed -n -e '/^PLAY RECAP/,$$p' +``` diff --git a/ansible_parallel.py b/ansible_parallel.py new file mode 100644 index 0000000..767d8ac --- /dev/null +++ b/ansible_parallel.py @@ -0,0 +1,111 @@ +import os +import asyncio +from time import perf_counter +import subprocess + + +import argparse + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("playbook", nargs="+") + return parser.parse_known_args() + + +async def run_playbook(playbook, args, results): + await results.put(("START", playbook, "")) + process = await asyncio.create_subprocess_exec( + "ansible-playbook", + playbook, + *args, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env={**os.environ, "ANSIBLE_FORCE_COLOR": "1"}, + ) + task = [] + while line := (await process.stdout.readline()).decode(): + if line == "\n": + chunk = "".join(task) + line + await results.put( + ("RECAP" if "PLAY RECAP" in chunk else "TASK", playbook, chunk) + ) + task = [] + else: + task.append(line) + if task: + chunk = "".join(task) + await results.put( + ("RECAP" if "PLAY RECAP" in chunk else "TASK", playbook, chunk) + ) + + await process.wait() + await results.put(("DONE", playbook, "")) + + +FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] + +DISABLE_CURSOR = "\033[?25l" +ENABLE_CURSOR = "\033[?25h" + + +def truncate(string, max_width=120): + if len(string) < max_width: + return string + return string[:max_width] + "…" + + +async def show_progression(results): + recaps = {} + starts = {} + ends = {} + currently_running = [] + frameno = 0 + print(DISABLE_CURSOR, end="") + try: + while result := await results.get(): + frameno += 1 + msgtype, playbook, msg = result + if msgtype == "START": + starts[playbook] = perf_counter() + currently_running.append(playbook) + if msgtype == "DONE": + currently_running.remove(playbook) + ends[playbook] = perf_counter() + if msgtype == "RECAP": + recaps[playbook] = msg + print( + FRAMES[frameno % len(FRAMES)], + f"{len(currently_running)} playbook{'s' if len(currently_running) > 1 else ''} running:", + f"{truncate(', '.join(currently_running))}", + end="\r", + ) + finally: + print(ENABLE_CURSOR, end="") + for playbook, recap in recaps.items(): + print( + f"# Playbook {playbook}, ran in {ends[playbook] - starts[playbook]:.0f}s", + end="\n\n", + ) + for line in recap.split("\n"): + if "PLAY RECAP" not in line: + print(line) + + +async def amain(): + args, remaining_args = parse_args() + results = asyncio.Queue() + asyncio.create_task(show_progression(results)) + await asyncio.gather( + *[run_playbook(playbook, remaining_args, results) for playbook in args.playbook] + ) + await results.put(None) + + +def main(): + asyncio.run(amain()) + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..9787c3b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..34d5eeb --- /dev/null +++ b/setup.cfg @@ -0,0 +1,28 @@ +[metadata] +name = ansible-parallel +# Format is YYYY.MM.DD (https://calver.org/) +version = 2020.10.22 +description = Run ansible playbooks in parallel. +long_description = file: README.md +long_description_content_type = text/markdown; charset=UTF-8 +author = Julien Palard +author_email = julien@palard.fr +url = https://github.com/meltygroup/ansible-parallel +license = MIT License +classifiers = + Development Status :: 4 - Beta + Intended Audience :: System Administrators + License :: OSI Approved :: MIT License + Natural Language :: English + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + +[options] +py_modules = ansible_parallel +python_requires = >= 3.6 + +[options.entry_points] +console_scripts = ansible-parallel=ansible_parallel:main diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..b908cbe --- /dev/null +++ b/setup.py @@ -0,0 +1,3 @@ +import setuptools + +setuptools.setup()