diff --git a/.ansible-lint b/.ansible-lint new file mode 100644 index 0000000..142c4ed --- /dev/null +++ b/.ansible-lint @@ -0,0 +1,24 @@ +--- +profile: moderate + +exclude_paths: + - .git/ + - .github/ + - tests/ + - venv/ + - venv-ansible-*/ + +skip_list: + - yaml[line-length] + - name[casing] + - var-naming[no-role-prefix] + - schema[meta] + +warn_list: + - experimental + - role-name + +enable_list: + - yaml + +use_default_rules: true diff --git a/.ansible/roles/docker-deploy b/.ansible/roles/docker-deploy new file mode 120000 index 0000000..803751d --- /dev/null +++ b/.ansible/roles/docker-deploy @@ -0,0 +1 @@ +/home/ibranco/projects/nau/ansible-docker-deploy \ No newline at end of file diff --git a/.ansible/roles/fccn.ansible_docker_deploy b/.ansible/roles/fccn.ansible_docker_deploy new file mode 120000 index 0000000..803751d --- /dev/null +++ b/.ansible/roles/fccn.ansible_docker_deploy @@ -0,0 +1 @@ +/home/ibranco/projects/nau/ansible-docker-deploy \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..07dee60 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,41 @@ +--- +name: Bug Report +about: Create a report to help us improve +title: '[BUG] ' +labels: bug +assignees: '' +--- + +## Description +A clear and concise description of the bug. + +## Environment +- **Ansible Version**: [e.g., 2.15.0] +- **OS**: [e.g., Ubuntu 22.04] +- **Docker Version**: [e.g., 24.0.0] +- **Docker Compose Version**: [e.g., 2.20.0] + +## Playbook/Variables +```yaml +# Paste your playbook or variable configuration here +# (Remove any sensitive information) +``` + +## Steps to Reproduce +1. Run playbook with... +2. Configure variable... +3. See error... + +## Expected Behavior +A clear description of what you expected to happen. + +## Actual Behavior +What actually happened. + +## Error Output +``` +Paste any error messages or logs here +``` + +## Additional Context +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e22f337 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,29 @@ +--- +name: Feature Request +about: Suggest an idea for this project +title: '[FEATURE] ' +labels: enhancement +assignees: '' +--- + +## Is your feature request related to a problem? +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +## Describe the solution you'd like +A clear and concise description of what you want to happen. + +## Describe alternatives you've considered +A clear and concise description of any alternative solutions or features you've considered. + +## Example Usage +```yaml +# Show how you would like to use this feature +``` + +## Additional context +Add any other context or screenshots about the feature request here. + +## Would you like to implement this feature? +- [ ] Yes, I can work on this +- [ ] No, but I can help test it +- [ ] No, just requesting diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b672426 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,32 @@ +# Pull Request + +## Description +Brief description of what this PR does. + +## Type of Change +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] Documentation update +- [ ] Test improvement + +## Testing +- [ ] All existing tests pass +- [ ] New tests added for new features +- [ ] Manual testing performed + +## Checklist +- [ ] My code follows the style guidelines of this project +- [ ] I have performed a self-review of my own code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] I have made corresponding changes to the documentation +- [ ] My changes generate no new warnings +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] New and existing unit tests pass locally with my changes +- [ ] CHANGELOG.md updated with my changes + +## Related Issues +Closes #(issue number) + +## Additional Notes +Any additional information that reviewers should know. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..338715f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,163 @@ +--- +name: CI + +on: + push: + branches: [ main, master, develop ] + pull_request: + branches: [ main, master, develop ] + workflow_dispatch: + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install ansible ansible-lint yamllint + + - name: Run yamllint + run: | + yamllint -c .yamllint . + continue-on-error: true + + - name: Run ansible-lint + run: | + ansible-lint + continue-on-error: true + + - name: Ansible syntax check + run: | + printf '[defaults]\nroles_path=../' > ansible.cfg + ansible-playbook tests/test.yml -i tests/inventory --syntax-check + + test-syntax: + name: Test Syntax (Ansible ${{ matrix.ansible-version }}) + runs-on: ubuntu-latest + strategy: + matrix: + ansible-version: + - '5' # ansible 5.x (includes ansible-core 2.12) + - '6' # ansible 6.x (includes ansible-core 2.13) + - '7' # ansible 7.x (includes ansible-core 2.14) + - '8' # ansible 8.x (includes ansible-core 2.15) + - '9' # ansible 9.x (includes ansible-core 2.16) + - 'latest' + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version || '3.11' }} + + - name: Install Ansible ${{ matrix.ansible-version }} + run: | + python -m pip install --upgrade pip + if [ "${{ matrix.ansible-version }}" = "latest" ]; then + pip install ansible + else + pip install "ansible~=${{ matrix.ansible-version }}.0" + fi + + - name: Display Ansible version + run: ansible --version + + - name: Syntax check + run: | + printf '[defaults]\nroles_path=../' > ansible.cfg + ansible-playbook tests/test.yml -i tests/inventory --syntax-check + + test-integration: + name: Integration Tests (Ansible ${{ matrix.ansible-version }}) + runs-on: ubuntu-latest + needs: [lint, test-syntax] + strategy: + matrix: + ansible-version: + - '5' # Oldest supported version + - '7' # Mid-range version + - '9' # Recent stable version + - 'latest' # Latest release + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version || '3.11' }} + + - name: Install Ansible ${{ matrix.ansible-version }} + run: | + python -m pip install --upgrade pip + if [ "${{ matrix.ansible-version }}" = "latest" ]; then + pip install ansible docker + else + pip install "ansible~=${{ matrix.ansible-version }}.0" docker + fi + + - name: Install Ansible collections + run: | + if [ "${{ matrix.ansible-version }}" = "5" ]; then + echo "Installing community.docker collection (workaround for Galaxy API issues with Ansible ${{ matrix.ansible-version }})" + ansible-galaxy collection install community.docker || echo "Collection install failed, but will continue with docker Python library" + else + ansible-galaxy collection install -r requirements.yml + fi + + - name: Display Ansible version + run: ansible --version + + - name: Setup test environment + run: | + printf '[defaults]\nroles_path=../' > ansible.cfg + + - name: Run tests + run: make test-all + + test-molecule: + name: Molecule Tests + runs-on: ubuntu-latest + needs: [lint] + steps: + - name: Check out code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install molecule molecule-plugins[docker] ansible docker + + - name: Run Molecule tests + run: | + molecule test + continue-on-error: true + working-directory: ${{ github.workspace }} + + notify: + name: Notify Ansible Galaxy + runs-on: ubuntu-latest + needs: [test-integration] + if: github.ref == 'refs/heads/master' && github.event_name == 'push' + steps: + - name: Trigger galaxy import + run: | + echo "Would notify Ansible Galaxy here" + # curl -X POST https://galaxy.ansible.com/api/v1/notifications/ diff --git a/.gitignore b/.gitignore index 5d51967..24fa295 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ ansible.cfg venv +venv-* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index a213902..0000000 --- a/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ ---- -language: python -python: "3.8" - -# Use the new container infrastructure -sudo: false - -# Install ansible -addons: - apt: - packages: - - python-pip - -install: - # Install ansible - - pip install ansible - - # Check ansible version - - ansible --version - - # Create ansible.cfg with correct roles_path - - printf '[defaults]\nroles_path=../' >ansible.cfg - -script: - # Basic role syntax check - - ansible-playbook tests/test.yml -i tests/inventory --syntax-check - -notifications: - webhooks: https://galaxy.ansible.com/api/v1/notifications/ diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..a1b4739 --- /dev/null +++ b/.yamllint @@ -0,0 +1,20 @@ +--- +extends: default + +rules: + line-length: + max: 160 + level: warning + comments: + min-spaces-from-content: 1 + comments-indentation: disable + document-start: disable + truthy: + allowed-values: ['true', 'false', 'yes', 'no'] + check-keys: false + +ignore: | + .github/ + .git/ + venv/ + venv-ansible-*/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3ae09cb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Comprehensive test suite with multiple test scenarios +- GitHub Actions CI/CD pipeline +- Molecule testing framework support +- Test runner script (`tests/run-tests.sh`) +- Linting configuration (yamllint, ansible-lint) +- CONTRIBUTING.md guide for contributors +- requirements.txt and requirements-dev.txt for development dependencies + +### Changed +- Improved README with real-world examples from NAU project +- Enhanced documentation with better structure and formatting + +### Removed +- Docker Swarm/Stack support (compose-only role now) +- Removed `docker_deploy_stack_template` variable +- Removed `docker_deploy_stack_name` variable +- Removed `docker_deploy_stack_pip_requirements` variable +- Removed `tasks/docker_deploy_stack.yml` task file + +## [1.0.0] - Previous Release + +### Added +- Initial support for Docker Compose deployments +- Docker Swarm/Stack deployment support +- File and template management +- Git repository cloning +- Docker configs and secrets support +- Health check functionality +- Custom deployment modes (shell vs Ansible module) + +[Unreleased]: https://github.com/fccn/ansible-docker-deploy/compare/v1.0.0...HEAD +[1.0.0]: https://github.com/fccn/ansible-docker-deploy/releases/tag/v1.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e8e66fc --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,265 @@ +# Contributing to ansible-docker-deploy + +Thank you for your interest in contributing to ansible-docker-deploy! + +## Getting Started + +1. Fork the repository on GitHub +2. Clone your fork locally: + ```bash + git clone https://github.com/YOUR-USERNAME/ansible-docker-deploy.git + cd ansible-docker-deploy + ``` + +3. Create a new branch for your feature or bugfix: + ```bash + git checkout -b feature/my-new-feature + ``` + +## Development Setup + +### Install Dependencies + +```bash +# Create a virtual environment +python3 -m venv venv +source venv/bin/activate # On Windows: venv\Scripts\activate + +# Install development dependencies +pip install -r requirements-dev.txt + +# Install Ansible collections +ansible-galaxy collection install -r requirements.yml +``` + +### Install Docker (if not already installed) + +- **Ubuntu/Debian:** + ```bash + sudo apt-get update + sudo apt-get install docker.io docker-compose + sudo systemctl start docker + sudo usermod -aG docker $USER + ``` + +- **macOS:** Install Docker Desktop from https://www.docker.com/products/docker-desktop + +- **Windows:** Install Docker Desktop from https://www.docker.com/products/docker-desktop + +## Testing + +### Quick Testing with Make + +```bash +# Run all tests (syntax check + linting + integration tests) +make test + +# Run specific test types +make syntax-check +make lint +make test-compose +make test-files +make test-secrets +``` + +### Testing Across Multiple Ansible Versions + +**Using Docker (Recommended - No local Ansible installation needed):** + +```bash +# Test all Ansible versions sequentially +make docker-test-all + +# Test all versions in parallel (much faster!) +make -j4 docker-test-all-parallel + +# Test specific version +make docker-test VERSION=9 +make docker-test VERSION=6 + +# Clean up Docker images when done +make docker-clean +``` + +**Using Virtual Environments:** + +Tests only versions compatible with your Python version: + +```bash +# Test all compatible versions sequentially +make test-all-versions + +# Test compatible versions in parallel +make -j3 test-all-versions-parallel + +# Test specific version (if compatible with your Python) +make test-ansible-version VERSION=9 + +# Clean up virtual environments +make clean-venvs +``` + +**Python/Ansible Compatibility Matrix:** +- Python 3.12: ✅ Ansible 7, 8, 9 +- Python 3.11: ✅ Ansible 7, 8, 9 +- Python 3.10: ✅ Ansible 5, 6, 7, 8, 9 +- Python 3.8-3.9: ✅ Ansible 5, 6, 7, 8, 9 + +Virtual environment tests automatically skip incompatible versions. For complete version coverage regardless of your Python version, use Docker-based testing. + +**Performance tip:** Use `-j4` or `-j8` for parallel execution to speed up testing significantly! + +### Run All Tests + +```bash +# From the project root +cd tests +./run-tests.sh +``` + +### Run Specific Tests + +```bash +# Syntax check +ansible-playbook tests/test.yml -i tests/inventory --syntax-check + +# Compose test +ansible-playbook tests/test-compose.yml -i tests/inventory -vv + +# Files and templates test +ansible-playbook tests/test-files-templates.yml -i tests/inventory -vv + +# Secrets and configs test +ansible-playbook tests/test-secrets-configs.yml -i tests/inventory -vv +``` + +### Run Linting + +```bash +# YAML linting +yamllint . + +# Ansible linting +ansible-lint + +# Both together (or use: make lint) +yamllint . && ansible-lint +``` + +### Run Molecule Tests + +```bash +# Full test suite +molecule test + +# Step by step +molecule create # Create test instance +molecule converge # Run the role +molecule verify # Run verification tests +molecule destroy # Clean up +``` + +## Code Style Guidelines + +### YAML Files + +- Use 2 spaces for indentation +- Maximum line length: 160 characters +- Always use `---` at the beginning of YAML files +- Use `true`/`false` for booleans (not `yes`/`no` unless in legacy code) + +### Ansible Tasks + +- Always include a descriptive `name` for tasks +- Use tags appropriately (`docker_deploy`, `healthcheck`, etc.) +- Add comments for complex logic +- Use `when` conditions to make tasks conditional +- Use `changed_when: false` for read-only tasks + +### Variables + +- Prefix role variables with `docker_deploy_` +- Use descriptive variable names +- Document all variables in `defaults/main.yml` +- Use sensible defaults + +## Pull Request Process + +1. **Update documentation** if you're adding new features or changing behavior +2. **Add tests** for new features +3. **Run the test suite** and ensure all tests pass: + ```bash + ./tests/run-tests.sh + yamllint . + ansible-lint + ``` +4. **Update CHANGELOG.md** with your changes +5. **Commit your changes** with clear, descriptive commit messages: + ```bash + git add . + git commit -m "Add feature: description of feature" + ``` +6. **Push to your fork**: + ```bash + git push origin feature/my-new-feature + ``` +7. **Create a Pull Request** on GitHub with: + - Clear title and description + - Reference to any related issues + - Screenshots if applicable + - Test results + +## Commit Message Guidelines + +- Use the present tense ("Add feature" not "Added feature") +- Use the imperative mood ("Move cursor to..." not "Moves cursor to...") +- Limit the first line to 72 characters +- Reference issues and pull requests after the first line + +Examples: +``` +Add support for custom healthcheck commands + +- Implement docker_deploy_healthcheck_command variable +- Update documentation with examples +- Add tests for custom healthcheck functionality + +Fixes #123 +``` + +## Issue Reporting + +When reporting issues, please include: + +- Your Ansible version (`ansible --version`) +- Your OS and version +- Docker version (`docker --version`) +- Complete error messages and stack traces +- Steps to reproduce the issue +- Expected vs actual behavior + +## Feature Requests + +Feature requests are welcome! Please: + +- Check if the feature has already been requested +- Clearly describe the feature and its use case +- Provide examples of how it would be used +- Consider contributing the feature yourself + +## Questions? + +- Open an issue for bugs or feature requests +- Check existing issues for similar questions +- Review the documentation in README.md + +## Code of Conduct + +- Be respectful and inclusive +- Welcome newcomers and help them get started +- Focus on what is best for the community +- Show empathy towards other community members + +## License + +By contributing, you agree that your contributions will be licensed under the GPL-3.0-only License. diff --git a/Dockerfile.test b/Dockerfile.test new file mode 100644 index 0000000..74c82f1 --- /dev/null +++ b/Dockerfile.test @@ -0,0 +1,61 @@ +# Multi-stage Dockerfile for testing different Ansible versions +ARG ANSIBLE_VERSION=latest +ARG PYTHON_VERSION=3.11 + +FROM python:${PYTHON_VERSION}-slim as base + +# Install system dependencies +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + git \ + openssh-client \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /roles/ansible-docker-deploy + +FROM base as ansible-5 +COPY requirements.yml ./ +RUN pip install --no-cache-dir "ansible~=5.0" && \ + ansible-galaxy collection install -r requirements.yml || echo "Warning: Collection install failed, continuing..." +COPY . . +RUN printf '[defaults]\nroles_path=/roles\n' > ansible.cfg + +FROM base as ansible-6 +COPY requirements.yml ./ +RUN pip install --no-cache-dir "ansible~=6.0" && \ + ansible-galaxy collection install -r requirements.yml || echo "Warning: Collection install failed, continuing..." +COPY . . +RUN printf '[defaults]\nroles_path=/roles\n' > ansible.cfg + +FROM base as ansible-7 +COPY requirements.yml ./ +RUN pip install --no-cache-dir "ansible~=7.0" && \ + ansible-galaxy collection install -r requirements.yml || echo "Warning: Collection install failed, continuing..." +COPY . . +RUN printf '[defaults]\nroles_path=/roles\n' > ansible.cfg + +FROM base as ansible-8 +COPY requirements.yml ./ +RUN pip install --no-cache-dir "ansible~=8.0" && \ + ansible-galaxy collection install -r requirements.yml || echo "Warning: Collection install failed, continuing..." +COPY . . +RUN printf '[defaults]\nroles_path=/roles\n' > ansible.cfg + +FROM base as ansible-9 +COPY requirements.yml ./ +RUN pip install --no-cache-dir "ansible~=9.0" && \ + ansible-galaxy collection install -r requirements.yml || echo "Warning: Collection install failed, continuing..." +COPY . . +RUN printf '[defaults]\nroles_path=/roles\n' > ansible.cfg + +FROM base as ansible-latest +COPY requirements.yml ./ +RUN pip install --no-cache-dir ansible && \ + ansible-galaxy collection install -r requirements.yml || echo "Warning: Collection install failed, continuing..." +COPY . . +RUN printf '[defaults]\nroles_path=/roles\n' > ansible.cfg + +# Default stage +FROM ansible-${ANSIBLE_VERSION} + +CMD ["ansible-playbook", "tests/test.yml", "-i", "tests/inventory", "--syntax-check"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2794924 --- /dev/null +++ b/Makefile @@ -0,0 +1,258 @@ +# Makefile for ansible-docker-deploy role +# +# This Makefile provides convenient targets for testing, linting, and managing +# the ansible-docker-deploy Ansible role. It supports: +# - Local testing with syntax checks, linting, and integration tests +# - Multi-version testing with virtual environments or Docker +# - Parallel test execution for faster CI/CD pipelines +# - Docker-based testing for complete Ansible version coverage +# +# Common targets: +# make test - Run all tests (syntax, lint, integration) +# make test-all - Run integration tests only +# make docker-test-all - Test all Ansible versions with Docker +# make -j4 docker-test-all-parallel - Parallel Docker testing (recommended) +# make help - Show all available targets + +help: ## Show this help message + @echo 'Usage: make [target]' + @echo '' + @echo 'Available targets:' + @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " %-20s %s\n", $$1, $$2}' $(MAKEFILE_LIST) +.PHONY: help + +install: ## Install development dependencies + pip install -r requirements-dev.txt +.PHONY: install + +test: syntax-check lint test-all ## Run all tests +.PHONY: test + +lint: ## Run linting (yamllint and ansible-lint) + @echo "Running yamllint..." + yamllint . + @echo "Running ansible-lint..." + ansible-lint +.PHONY: lint + +syntax-check: ## Run Ansible syntax check + @echo "Running syntax check..." + printf '[defaults]\nroles_path=../' > ansible.cfg + ansible-playbook tests/test.yml -i tests/inventory --syntax-check +.PHONY: syntax-check + +test-all: test-compose test-files test-secrets test-compose-v2 test-files-v2 test-secrets-v2 ## Run all integration tests (both shell and docker_compose_v2 modes) + @echo "All integration tests completed!" +.PHONY: test-all + +test-compose: ## Run compose deployment test (shell mode) + @echo "Running compose deployment test (shell mode)..." + ansible-playbook tests/test-compose.yml -i tests/inventory -vv +.PHONY: test-compose + +test-files: ## Run files and templates test (shell mode) + @echo "Running files and templates test (shell mode)..." + ansible-playbook tests/test-files-templates.yml -i tests/inventory -vv +.PHONY: test-files + +test-secrets: ## Run secrets and configs test (shell mode) + @echo "Running secrets and configs test (shell mode)..." + ansible-playbook tests/test-secrets-configs.yml -i tests/inventory -vv +.PHONY: test-secrets + +test-compose-v2: ## Run compose deployment test (docker_compose_v2 mode) + @echo "Running compose deployment test (docker_compose_v2 mode)..." + ansible-playbook tests/test-compose-v2.yml -i tests/inventory -vv +.PHONY: test-compose-v2 + +test-files-v2: ## Run files and templates test (docker_compose_v2 mode) + @echo "Running files and templates test (docker_compose_v2 mode)..." + ansible-playbook tests/test-files-templates-v2.yml -i tests/inventory -vv +.PHONY: test-files-v2 + +test-secrets-v2: ## Run secrets and configs test (docker_compose_v2 mode) + @echo "Running secrets and configs test (docker_compose_v2 mode)..." + ansible-playbook tests/test-secrets-configs-v2.yml -i tests/inventory -vv +.PHONY: test-secrets-v2 + +molecule: ## Run molecule tests + @echo "Running molecule tests..." + molecule test +.PHONY: molecule + +molecule-converge: ## Run molecule converge + molecule converge +.PHONY: molecule-converge + +molecule-verify: ## Run molecule verify + molecule verify +.PHONY: molecule-verify + +molecule-destroy: ## Destroy molecule instances + molecule destroy +.PHONY: molecule-destroy + +clean: ## Clean up test artifacts and Docker resources + @echo "Cleaning up..." + rm -rf ansible.cfg + docker stop $$(docker ps -aq) 2>/dev/null || true + docker rm $$(docker ps -aq) 2>/dev/null || true + docker swarm leave --force 2>/dev/null || true + rm -rf /tmp/ansible-docker-deploy-test* +.PHONY: clean + +setup: ## Setup development environment + python3 -m venv venv + ./venv/bin/pip install -r requirements-dev.txt + ansible-galaxy collection install -r requirements.yml + @echo "Development environment ready!" + @echo "Activate it with: source venv/bin/activate" +.PHONY: setup + +test-ansible-version: ## Test with specific Ansible version (usage: make test-ansible-version VERSION=9) + @if [ -z "$(VERSION)" ]; then \ + echo "Error: VERSION not specified. Usage: make test-ansible-version VERSION=9"; \ + exit 1; \ + fi + @echo "Testing with Ansible $(VERSION)..." + @python_version=$$(python3 --version | awk '{print $$2}' | cut -d. -f1,2); \ + if [ "$(VERSION)" = "5" ] || [ "$(VERSION)" = "6" ]; then \ + if [ "$$(echo "$$python_version >= 3.11" | bc)" -eq 1 ]; then \ + echo "WARNING: Ansible $(VERSION) is not compatible with Python $$python_version"; \ + echo "Ansible 5-6 require Python <= 3.10. Skipping test."; \ + exit 0; \ + fi; \ + fi + python3 -m venv venv-ansible-$(VERSION) + ./venv-ansible-$(VERSION)/bin/pip install --upgrade pip + ./venv-ansible-$(VERSION)/bin/pip install "ansible~=$(VERSION).0" + ./venv-ansible-$(VERSION)/bin/ansible --version + @echo "Installing community.docker collection..." + @if [ "$(VERSION)" = "5" ]; then \ + echo "Note: Using direct installation method for Ansible $(VERSION) due to Galaxy API compatibility"; \ + ./venv-ansible-$(VERSION)/bin/ansible-galaxy collection install community.docker || \ + ./venv-ansible-$(VERSION)/bin/pip install docker; \ + else \ + ./venv-ansible-$(VERSION)/bin/ansible-galaxy collection install -r requirements.yml; \ + fi + printf '[defaults]\nroles_path=../' > ansible.cfg + ./venv-ansible-$(VERSION)/bin/ansible-playbook tests/test.yml -i tests/inventory --syntax-check + @echo "Ansible $(VERSION) tests completed!" +.PHONY: test-ansible-version + +test-all-versions: ## Test against all supported Ansible versions (compatible with current Python) + @echo "Testing against multiple Ansible versions..." + @python_version=$$(python3 --version | awk '{print $$2}' | cut -d. -f1,2); \ + if [ "$$(echo "$$python_version >= 3.11" | bc)" -eq 1 ]; then \ + echo "Python $$python_version detected: Testing Ansible 7, 8, 9 (compatible versions)"; \ + versions="7 8 9"; \ + else \ + echo "Python $$python_version detected: Testing Ansible 5-9"; \ + versions="5 6 7 8 9"; \ + fi; \ + for version in $$versions; do \ + echo ""; \ + echo "========================================"; \ + echo "Testing Ansible $$version"; \ + echo "========================================"; \ + $(MAKE) test-ansible-version VERSION=$$version || exit 1; \ + done + @echo "" + @echo "All version tests completed successfully!" +.PHONY: test-all-versions + +# Individual version targets for parallel execution +test-ansible-5: + @$(MAKE) test-ansible-version VERSION=5 +.PHONY: test-ansible-5 + +test-ansible-6: + @$(MAKE) test-ansible-version VERSION=6 +.PHONY: test-ansible-6 + +test-ansible-7: + @$(MAKE) test-ansible-version VERSION=7 +.PHONY: test-ansible-7 + +test-ansible-8: + @$(MAKE) test-ansible-version VERSION=8 +.PHONY: test-ansible-8 + +test-ansible-9: + @$(MAKE) test-ansible-version VERSION=9 +.PHONY: test-ansible-9 + +test-all-versions-parallel: test-ansible-7 test-ansible-8 test-ansible-9 ## Test compatible versions in parallel (use with make -j3) + @echo "" + @echo "All parallel version tests completed!" + @echo "Note: Use Docker tests for full version coverage: make -j4 docker-test-all-parallel" +.PHONY: test-all-versions-parallel + +clean-venvs: ## Remove all test virtual environments + @echo "Removing test virtual environments..." + rm -rf venv-ansible-* +.PHONY: clean-venvs + +# Docker-based testing targets +docker-test: ## Run tests in Docker for specific Ansible version (usage: make docker-test VERSION=9) + @if [ -z "$(VERSION)" ]; then \ + echo "Error: VERSION not specified. Usage: make docker-test VERSION=9"; \ + exit 1; \ + fi + ./docker-test.sh $(VERSION) +.PHONY: docker-test + +docker-test-all: ## Run tests in Docker for all Ansible versions + ./docker-test.sh all +.PHONY: docker-test-all + +# Individual Docker test targets for parallel execution +docker-test-5: + @./docker-test.sh 5 +.PHONY: docker-test-5 + +docker-test-6: + @./docker-test.sh 6 +.PHONY: docker-test-6 + +docker-test-7: + @./docker-test.sh 7 +.PHONY: docker-test-7 + +docker-test-8: + @./docker-test.sh 8 +.PHONY: docker-test-8 + +docker-test-9: + @./docker-test.sh 9 +.PHONY: docker-test-9 + +docker-test-latest: + @./docker-test.sh latest +.PHONY: docker-test-latest + +docker-test-all-parallel: docker-test-5 docker-test-6 docker-test-7 docker-test-8 docker-test-9 docker-test-latest ## Run Docker tests in parallel (use with make -j4) + @echo "" + @echo "All parallel Docker tests completed!" +.PHONY: docker-test-all-parallel + +docker-test-syntax: ## Run syntax check in Docker (usage: make docker-test-syntax VERSION=9) + @if [ -z "$(VERSION)" ]; then \ + echo "Error: VERSION not specified. Usage: make docker-test-syntax VERSION=9"; \ + exit 1; \ + fi + ./docker-test.sh $(VERSION) 3.11 syntax +.PHONY: docker-test-syntax + +docker-test-compose: ## Run compose test in Docker (usage: make docker-test-compose VERSION=9) + @if [ -z "$(VERSION)" ]; then \ + echo "Error: VERSION not specified. Usage: make docker-test-compose VERSION=9"; \ + exit 1; \ + fi + ./docker-test.sh $(VERSION) 3.11 test-compose +.PHONY: docker-test-compose + +docker-clean: ## Clean up Docker test images + @echo "Removing Docker test images..." + docker rmi $(shell docker images -q ansible-docker-deploy-test) 2>/dev/null || true +.PHONY: docker-clean diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 0000000..36ad9c7 --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,118 @@ +# Quick Start Guide + +## Installation + +### From Ansible Galaxy +```bash +ansible-galaxy install fccn.ansible-docker-deploy +``` + +### From GitHub +```bash +ansible-galaxy install git+https://github.com/fccn/ansible-docker-deploy.git +``` + +## Minimal Example + +```yaml +- hosts: servers + roles: + - role: fccn.ansible-docker-deploy + vars: + docker_deploy_compose_template: "templates/docker-compose.yml.j2" + docker_deploy_base_folder: /opt/myapp + docker_deploy_shell: true +``` + +## Common Use Cases + +### 1. Deploy with Environment File + +```yaml +docker_deploy_templates: + - src: templates/.env.j2 + dest: "{{ docker_deploy_base_folder }}/.env" +``` + +### 2. Deploy with Secrets + +```yaml +docker_deploy_templates: + - src_data: "{{ database_password }}" + dest: "{{ docker_deploy_base_folder }}/db-password" + secret_name: db_password + service: app + docker_target: /run/secrets/db-password +``` + +### 3. Deploy with Git Repository + +```yaml +docker_deploy_git_repositories: + - repo: https://github.com/example/app.git + dest: "{{ docker_deploy_base_folder }}/app" + version: v1.0.0 + force: true +``` + +### 4. Deploy with Custom Folders + +```yaml +docker_deploy_folders_additional: + - dest: /data/app/uploads + dir_owner: 33 # www-data + dir_group: 33 + dir_mode: "0755" +``` + +### 5. Deploy with Health Check + +```yaml +docker_deploy_healthcheck_delay: 10 +docker_deploy_healthcheck_retries: 30 +``` + +## Testing Your Deployment + +```bash +# Quick syntax check +make syntax-check + +# Run all tests +make test + +# Test with different Ansible versions using Docker +make docker-test-all + +# Test in parallel (faster!) +make -j4 docker-test-all-parallel + +# Run specific test +make test-compose +``` + +## Troubleshooting + +### Container doesn't start +Check logs: `docker logs ` + +### Permission issues +Verify folder ownership in `docker_deploy_folders_additional` + +### Template not rendering +Check that all variables are defined in your playbook + +## More Examples + +See [README.md](README.md) for comprehensive examples including: +- MySQL deployment with replication +- Elasticsearch cluster setup +- MongoDB with authentication +- Redis with resource limits +- Wrapper role patterns + +## Getting Help + +- 📖 [Full Documentation](README.md) +- 🐛 [Report Issues](https://github.com/fccn/ansible-docker-deploy/issues) +- 💬 [Discussions](https://github.com/fccn/ansible-docker-deploy/discussions) diff --git a/README.md b/README.md index dc14dce..f782a26 100644 --- a/README.md +++ b/README.md @@ -1,192 +1,517 @@ # Ansible Docker Deploy +[![CI](https://github.com/fccn/ansible-docker-deploy/workflows/CI/badge.svg)](https://github.com/fccn/ansible-docker-deploy/actions) +[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) +[![Ansible Role](https://img.shields.io/ansible/role/XXXXX)](https://galaxy.ansible.com/fccn/ansible-docker-deploy) -Ansible utility role to easily deploy a docker compose or stack. It copies, templates and git clones a repository and then deploys the software using docker compose/stack. Additionally waits for containers to become healthy. +Ansible utility role to easily deploy Docker Compose applications. It handles copying files, rendering templates, cloning git repositories, and deploying containers using docker-compose. The role also includes health check monitoring to ensure containers start successfully. -This role doesn't install docker, docker compose or docker stack. The focus is the deployment of containers. +**Note:** This role does not install Docker or Docker Compose. It focuses solely on deploying and managing containerized applications. -## Requirements +## Features +- 🐳 **Docker Compose Deployment** - Deploy applications using docker-compose +- 📦 **Asset Management** - Copy files, render templates, and clone git repositories +- 🔐 **Secrets & Configs** - Manage Docker secrets and configs with automatic checksums +- ✅ **Health Checks** - Built-in container health monitoring +- 🎯 **Flexible Modes** - Use Ansible modules or direct shell commands +- 🔧 **Wrapper-Friendly** - Easy to wrap for service-specific roles -Only ansible. +## Requirements -Compatible with ansible 2.7 (only docker-compose) and 2.9. +- Ansible 2.7 or higher +- Docker and Docker Compose installed on target hosts +- `community.docker` Ansible collection (for docker_compose_v2 module) + ```bash + ansible-galaxy collection install community.docker + ``` +- Python `docker` module (for non-shell mode) + ```bash + pip install docker + ``` + +**Note:** If `community.docker` collection is not available, the role will automatically fall back to shell-based deployment mode. ## Role Variables +### Required Variables + +At minimum, you must define one of the following: +- **`docker_deploy_compose_template`** - Path to your docker-compose.yml template file +- **`docker_deploy_shell_start`** - Custom shell command to start containers + +### Core Variables -The `docker_deploy_base_folder` variable is the destination of the docker-compose.yml or docker-stack.yml file. -The idea is to be the base directory where everything goes to the target machine. +- **`docker_deploy_base_folder`** (default: `/opt/docker-deploy`) - Destination directory on the target machine where the docker-compose.yml and all related files will be deployed -Variables that can be used to copy, template or git clone a list of those assets using the variables: -* `docker_deploy_files` - copy files, default value `[]`; -* `docker_deploy_templates` - list of templates, default value `[]`; -* `docker_deploy_git_repositories` - to clone a list of repositories, default value `[]`; +### Asset Management -You can get the git version of the git of each `docker_deploy_git_repositories` by adding an attribute `fact` so the role define a new fact that could be used within the templates or within the compose. -You can use a specific ssh key to clone the git repository if you define a `ssh_key` +The role provides flexible ways to manage your deployment assets: -This role can deploy a docker compose to the ansible target server or a docker stack to a docker swarm. +- **`docker_deploy_files`** (default: `[]`) - List of files to copy to the target host +- **`docker_deploy_templates`** (default: `[]`) - List of Jinja2 templates to render on the target host +- **`docker_deploy_git_repositories`** (default: `[]`) - List of git repositories to clone -The next 2 variables decide the mode of the deploy, or a compose or a stack:: -* `docker_deploy_compose_template` - deploy a docker compose to the target ansible server -* `docker_deploy_stack_template` - deploy a docker stack to the docker swarm +#### Git Repository Options -### Compose mode +Each repository in `docker_deploy_git_repositories` can have: +- `repo` - Repository URL (required) +- `dest` - Destination path (required) +- `version` - Branch, tag, or commit (default: `master`) +- `force` - Force clone/update (default: `false`) +- `ssh_key` - SSH private key content for authentication +- `fact` - Define an Ansible fact with the checked out git version -If you define `docker_deploy_compose_template` variable, the role by default would use the ansible -role `docker_service`. But because ansible only supports the docker-compose '2' specification, this -role has an additional option that use the `docker-compose up` command directly. -So if you need to use the docker-compose syntax > 2.0, you need to assign `true` to the variable -`docker_deploy_shell`. +### Deployment Mode -* `docker_deploy_shell_start_default` - by default uses the command -`docker-compose pull && docker-compose build && docker-compose up -d` that pull's, build's and -startup the compose. -If you want to `--force-recreate` if any file, template or git -repository has changed. You can should add `--force-recreate` to the -`docker_deploy_shell_start_default_additional_parameters_if_changed` ansible variable. -If you want to always add parameters to the docker-compose command you should use the -`docker_deploy_shell_start_default_additional_parameters` ansible variable. +The role supports two deployment modes: -* `docker_deploy_force_restart` - to forcefully restart / recreate the containers +#### 1. Ansible Docker Compose Module Mode (default) -### Stack mode +By default, the role uses Ansible's `docker_compose` module. -To execute this ansible role using the docker stack mode, you need to defined the variable: -* `docker_deploy_stack_template` - the file to be templated that contains the docker stack definition. +#### 2. Shell Command Mode -Optional parameter: -* `docker_deploy_stack_name` - the name of the stack, by default uses the basename of the folder defined in the `docker_deploy_base_folder` variable. +For Docker Compose file format version 3.x or higher, set `docker_deploy_shell: true` to use direct shell commands. + +**Shell Mode Variables:** + +- **`docker_deploy_shell`** (default: `false`) - Enable shell command mode +- **`docker_deploy_shell_start_default`** (default: `docker-compose pull && docker-compose build && docker-compose up -d`) - Default startup command +- **`docker_deploy_shell_start_default_additional_parameters`** - Additional parameters always added to docker-compose commands +- **`docker_deploy_shell_start_default_additional_parameters_if_changed`** - Parameters added only when files change (e.g., `--force-recreate`) +- **`docker_deploy_force_restart`** - Force container recreation/restart ## Advanced parameters -Each template defined in `docker_deploy_templates` or file defined in `docker_deploy_files` can have a attribute `config_name` and/or `secret_name` that makes this ansible role to create a docker config or a docker secret. +### Docker Configs and Secrets + +Each item in `docker_deploy_templates` or `docker_deploy_files` can include a `config_name` and/or `secret_name` attribute to create Docker configs or secrets. + +Docker configs and secrets are immutable - once created, they cannot be updated. The standard workaround is to suffix each config/secret name with a checksum. This role automates this pattern by generating Ansible facts for each config/secret with their checksums: -Because the docker config and secrets are idempotent, you can't easily update them. The solution documented in multiple forums is to suffix each config/secret with a checksum. This ansible role make this pattern more easily by defining an ansible fact (variable) to each templated / copied docker config or secret. -Example: -* `docker_deploy_config__` -* `docker_deploy_secret__` +- `docker_deploy_config__` +- `docker_deploy_secret__` +**Example Configuration:** ```yml -... +docker_deploy_templates: + - src: files/nginx.conf.j2 + dest: /opt/nginx.conf + config_name: nginx_conf + docker_target: /etc/mysql/conf.d/mysql.cnf +``` + +**Example Usage in docker-compose.yml template:** + +```yml +services: + app: configs: - - source: my_config_name_{{ hostvars[inventory_hostname]['docker_deploy_config_' + docker_deploy_stack_name + '_' + 'my_config_name' ][:10] }} + - source: nginx_conf_{{ hostvars[inventory_hostname]['docker_deploy_config_' + _docker_deploy_name + '_nginx_conf'][:10] }} target: /etc/mysql/conf.d/mysql.cnf -... + configs: {% for template in ( docker_deploy_templates | selectattr('config_name', 'defined') | list ) %} - my_config_name_{{ hostvars[inventory_hostname]['docker_deploy_config_' + docker_deploy_stack_name + '_' + 'my_config_name' ][:10] }}: + {{ template.config_name }}_{{ hostvars[inventory_hostname]['docker_deploy_config_' + _docker_deploy_name + '_' + template.config_name][:10] }}: file: {{ template.dest }} {% endfor %} -... ``` +**Note:** You can also use the helper macros in `templates/_docker_deploy_helper.j2` to simplify config and secret generation. + ## Dependencies -Any. Only ansible. +None. Only Ansible is required. ## Example Playbook -Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too: +### Example 1: Basic Deployment + +Simple deployment with just a compose template: -Example 1: ```yml - - hosts: servers - roles: - - role: ansible-docker-deploy - vars: - docker_deploy_compose_template: "path_to/docker-compose.yml" +- hosts: servers + roles: + - role: ansible-docker-deploy + vars: + docker_deploy_compose_template: "path_to/docker-compose.yml" ``` -Example 2: +### Example 2: Deployment with Files and Templates + +Deploy with additional configuration files: + ```yml - hosts: servers roles: - - role: ansible-docker-deploy - vars: - docker_deploy_compose_template: "path_to/docker-compose.yml" - docker_deploy_files: - - src: "local_path/cert.key.pem" - dest: "{{ docker_deploy_base_folder }}/cert.key.pem" - docker_deploy_templates: - - src: "local_path/nginx.conf" - dest: "{{ docker_deploy_base_folder }}/nginx.conf" - - src: "local_path/Makefile" - dest: "{{ docker_deploy_base_folder }}/Makefile" - ``` - -Example 3: + - role: ansible-docker-deploy + vars: + docker_deploy_compose_template: "path_to/docker-compose.yml" + docker_deploy_files: + - src: "local_path/cert.key.pem" + dest: "{{ docker_deploy_base_folder }}/cert.key.pem" + docker_deploy_templates: + - src: "local_path/nginx.conf" + dest: "{{ docker_deploy_base_folder }}/nginx.conf" + - src: "local_path/Makefile" + dest: "{{ docker_deploy_base_folder }}/Makefile" +``` + +### Example 3: Deployment with Git Repository + +**Group vars:** +```yml +docker_deploy_compose_template: "path_to/docker-compose.yml" +docker_deploy_git_repositories: + - repo: https://github.com/fccn/wp-nau-theme.git + dest: "{{ wordpress_nau_theme_dest }}" + version: "{{ wordpress_nau_theme_version | default('master') }}" + force: true + owner: www-data + group: www-data + mode: u=rwX,g=rX,o=rX + fact: wordpress_nau_theme_git_version + # ssh_key: "{{ SSH_KEY_CONTENT }}" +``` -group vars +**Playbook:** ```yml - docker_deploy_compose_template: "path_to/docker-compose.yml" - docker_deploy_git_repositories: - - repo: https://github.com/fccn/wp-nau-theme.git - dest: "{{ wordpress_nau_theme_dest }}" - version: "{{ wordpress_nau_theme_version | default('master') }}" - force: true - owner: www-data - group: www-data - mode: u=rwX,g=rX,o=rX - fact: wordpress_nau_theme_git_version - # ssh_key: "{{ SSH_KEY_CONTENT }}" -``` - -playbook +- hosts: servers + roles: + - ansible-docker-deploy +``` + +### Example 4: MySQL Deployment with Secrets + +Real-world example deploying MySQL with Docker secrets and configs: + ```yml - hosts: servers - roles: - - ansible-docker-deploy +- hosts: mysql_servers + roles: + - role: ansible-docker-deploy + vars: + docker_deploy_base_folder: /nau/ops/mysql + docker_deploy_compose_template: templates/docker-compose.yml.j2 + docker_deploy_shell: true + docker_deploy_templates: + - src_data: "{{ mysql_root_password }}" + dest: "{{ docker_deploy_base_folder }}/mysql-root-password" + secret_name: mysql_root_password + service: mysql + docker_target: /run/secrets/mysql-root-password + - src: templates/mysql.cnf.j2 + dest: "{{ docker_deploy_base_folder }}/mysql.cfg" + config_name: mysql_cfg + service: mysql + docker_target: /etc/mysql/conf.d/mysql.cnf + - src: templates/Makefile + dest: "{{ docker_deploy_base_folder }}/Makefile" + docker_deploy_folders_additional: + - dest: /data/mysql/ + dir_owner: 999 + dir_group: root + dir_mode: "0755" ``` -Example 4: +### Example 5: Elasticsearch Cluster Deployment + +Deploy Elasticsearch with custom network configuration and health checks: -group vars ```yml - docker_deploy_stack_template: "path_to/docker-stack.yml" - docker_deploy_stack_name: wordpress - docker_deploy_git_repositories: - - repo: https://github.com/fccn/wp-nau-theme.git - dest: "{{ wordpress_nau_theme_dest }}" - version: "{{ wordpress_nau_theme_version | default('master') }}" - force: true - owner: www-data - group: www-data - mode: u=rwX,g=rX,o=rX - fact: wordpress_nau_theme_git_version - # ssh_key: "{{ SSH_KEY_CONTENT }}" -``` - -playbook +- hosts: elasticsearch_servers + roles: + - role: ansible-docker-deploy + vars: + docker_deploy_base_folder: /nau/ops/elasticsearch + docker_deploy_compose_template: templates/docker-compose.yml.j2 + docker_deploy_shell: true + docker_deploy_healthcheck_delay: 5 + docker_deploy_healthcheck_retries: 50 + docker_deploy_templates: + - src: templates/Makefile + dest: "{{ docker_deploy_base_folder }}/Makefile" + docker_deploy_folders_additional: + - dest: /data/elasticsearch/ + dir_owner: 1000 + dir_group: 1000 + dir_mode: "0755" +``` + +### Example 6: MongoDB with Replication + +Deploy MongoDB with authentication secrets and replication key: + ```yml - hosts: servers - roles: - - ansible-docker-deploy +- hosts: mongo_servers + roles: + - role: ansible-docker-deploy + vars: + docker_deploy_base_folder: /nau/ops/mongo + docker_deploy_compose_template: templates/docker-compose.yml.j2 + docker_deploy_shell: true + docker_deploy_templates: + - src_data: "{{ mongo_root_username }}" + dest: "{{ docker_deploy_base_folder }}/mongo/mongo-root-username" + secret_name: mongo_root_username + service: mongo + docker_target: /run/secrets/mongo-root-username + when: "{{ mongo_root_username | length > 0 }}" + - src_data: "{{ mongo_root_password }}" + dest: "{{ docker_deploy_base_folder }}/mongo/mongo-root-password" + secret_name: mongo_root_password + service: mongo + docker_target: /run/secrets/mongo-root-password + when: "{{ mongo_root_password | length > 0 }}" + - src_data: "{{ mongo_keyfile_value }}" + dest: "{{ docker_deploy_base_folder }}/mongo/mongodb_key" + mode: "0600" + owner: 999 + secret_name: mongo_key + service: mongo + docker_target: /run/secrets/mongodb_key + when: "{{ mongo_keyfile_value | length > 0 }}" +``` + +### Example 7: Redis with Resource Limits + +Deploy Redis with custom ulimits: + +```yml +- hosts: redis_servers + roles: + - role: ansible-docker-deploy + vars: + docker_deploy_base_folder: /nau/ops/redis + docker_deploy_compose_template: templates/docker-compose.yml.j2 + docker_deploy_shell: true + docker_deploy_healthcheck_delay: 10 + docker_deploy_healthcheck_retries: 360 + docker_deploy_templates: + - src: templates/Makefile + dest: "{{ docker_deploy_base_folder }}/Makefile" + docker_deploy_folders_additional: + - dest: /data/redis/ + dir_owner: 1001 + dir_group: 1001 + dir_mode: "0755" ``` +### Example 8: Wrapper Role Pattern + +Create a wrapper role that uses ansible-docker-deploy: + +**roles/mysql_docker_deploy/tasks/main.yml:** +```yml +--- +- name: Install required packages + package: + name: "{{ item }}" + state: present + loop: + - make + - python3-pip + - mysql-client + +- name: Deploy MySQL using ansible-docker-deploy + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ mysql_docker_deploy_base_folder }}" + docker_deploy_compose_template: "{{ mysql_docker_deploy_compose_template }}" + docker_deploy_templates: "{{ mysql_docker_deploy_templates | default([]) }}" + docker_deploy_files: "{{ mysql_docker_deploy_files | default([]) }}" + docker_deploy_folders_additional: "{{ mysql_docker_deploy_folders_additional | default([]) }}" + docker_deploy_shell: true + docker_deploy_healthcheck_delay: "{{ mysql_docker_deploy_healthcheck_delay }}" + docker_deploy_healthcheck_retries: "{{ mysql_docker_deploy_healthcheck_retries }}" + +- name: Run custom healthcheck + shell: make healthcheck + args: + chdir: "{{ mysql_docker_deploy_base_folder }}" + delay: "{{ mysql_docker_deploy_healthcheck_delay }}" + register: result + until: result.rc == 0 + retries: "{{ mysql_docker_deploy_healthcheck_retries }}" + changed_when: false + when: not ansible_check_mode +``` + +## Testing + +### Quick Syntax Check -## Test this role +To quickly test the role syntax: -To test the syntax run: ```bash virtualenv venv -. venv/bin/activate -pip install ansible==2.7.12 -printf '[defaults]\nroles_path=../' >ansible.cfg +source venv/bin/activate +pip install ansible +printf '[defaults]\nroles_path=../' > ansible.cfg ansible-playbook tests/test.yml -i tests/inventory --syntax-check ``` +### Comprehensive Test Suite + +The role includes a comprehensive test suite with multiple test scenarios: + +**Shell Mode Tests:** +1. **test-compose.yml** - Tests basic Docker Compose deployment (shell mode) +2. **test-files-templates.yml** - Tests file copying and template rendering (shell mode) +3. **test-secrets-configs.yml** - Tests Docker secrets and configs functionality (shell mode) + +**docker_compose_v2 Module Tests:** +4. **test-compose-v2.yml** - Tests basic Docker Compose deployment (docker_compose_v2 mode) +5. **test-files-templates-v2.yml** - Tests file copying and template rendering (docker_compose_v2 mode) +6. **test-secrets-configs-v2.yml** - Tests Docker secrets and configs functionality (docker_compose_v2 mode) + +#### Quick Start - Using Makefile + +```bash +# Run all tests (both shell and docker_compose_v2 modes) +make test + +# Run specific shell mode tests +make syntax-check +make lint +make test-compose +make test-files +make test-secrets + +# Run specific docker_compose_v2 mode tests +make test-compose-v2 +make test-files-v2 +make test-secrets-v2 +``` + +#### Testing with Multiple Ansible Versions + +**Option 1: Docker-based testing (Recommended)** + +No need to install different Ansible versions - everything runs in Docker: + +```bash +# Test all Ansible versions (4, 5, 6, 7, 8, 9, latest) +make docker-test-all + +# Test all versions in parallel (faster!) +make -j4 docker-test-all-parallel + +# Test specific version +make docker-test VERSION=9 +make docker-test VERSION=6 + +# Clean up Docker images +make docker-clean +``` + +**Option 2: Virtual environment testing** + +Tests only versions compatible with your current Python: +- **Python 3.12**: Ansible 7, 8, 9 +- **Python 3.11**: Ansible 7, 8, 9 +- **Python 3.10 or older**: Ansible 5, 6, 7, 8, 9 + +```bash +# Test all compatible versions sequentially +make test-all-versions + +# Test compatible versions in parallel +make -j3 test-all-versions-parallel + +# Test specific version (if compatible) +make test-ansible-version VERSION=9 + +# Clean up virtual environments +make clean-venvs +``` + +**Python/Ansible Compatibility:** +- Ansible 5-6: Python 3.8 - 3.10 +- Ansible 7-8: Python 3.9 - 3.11 +- Ansible 9+: Python 3.10 - 3.12 + +**Note:** Virtual env tests automatically skip incompatible versions. For full version coverage, use Docker-based testing. + +#### Running All Tests + +```bash +cd tests +./run-tests.sh +``` + +#### Running Individual Tests + +```bash +# Shell mode tests +ansible-playbook tests/test-compose.yml -i tests/inventory -vv +ansible-playbook tests/test-files-templates.yml -i tests/inventory -vv +ansible-playbook tests/test-secrets-configs.yml -i tests/inventory -vv + +# docker_compose_v2 mode tests +ansible-playbook tests/test-compose-v2.yml -i tests/inventory -vv +ansible-playbook tests/test-files-templates-v2.yml -i tests/inventory -vv +ansible-playbook tests/test-secrets-configs-v2.yml -i tests/inventory -vv +``` + +### Molecule Testing + +For more advanced testing with Molecule: + +```bash +# Install molecule +pip install molecule molecule-plugins[docker] docker + +# Run all molecule tests +molecule test + +# Run specific steps +molecule create +molecule converge +molecule verify +molecule destroy +``` + +### GitHub Actions CI/CD + +This role includes a comprehensive GitHub Actions workflow that automatically: + +- Runs linting (yamllint, ansible-lint) +- Tests syntax across multiple Ansible versions (4 - 9) +- Executes integration tests +- Runs Molecule tests +- Notifies Ansible Galaxy on successful master branch builds + +The CI pipeline is triggered on: +- Push to main/master/develop branches +- Pull requests to main/master/develop branches +- Manual workflow dispatch + +View the workflow in [.github/workflows/ci.yml](.github/workflows/ci.yml) + +### Test Requirements + +- Docker and Docker Compose installed +- Python 3.8+ +- Ansible 5.0+ +- ansible-lint and yamllint (for linting) +- molecule and molecule-docker (for Molecule tests) + ## License -GPLv3 +[GNU General Public License v3.0](LICENSE) + +## Author Information + +Created and maintained by **Ivo Branco** at [FCCN](https://www.fccn.pt/). + +## Contributing + +Contributions are welcome! Please open an issue or submit a pull request. + +--- -Author Information ------------------- +**Repository**: [fccn/ansible-docker-deploy](https://github.com/fccn/ansible-docker-deploy) -Ivo Branco -* https://www.fccn.pt -* https://arquivo.pt -* https://www.nau.edu.pt -* https://educast.fccn.pt diff --git a/defaults/main.yml b/defaults/main.yml index 8356d54..03e8f99 100644 --- a/defaults/main.yml +++ b/defaults/main.yml @@ -3,13 +3,13 @@ docker_deploy_base_folder: "/opt/docker-deploy" # Optional parameters # docker_deploy_compose_template: "docker-compose.yml.j2" -# docker_deploy_stack_template: docker-stack.yml -# To use docker-compose up / down using shell instead of docker-compose ansible role +# To use docker-compose up / down using shell instead of Ansible docker_compose module +# If not set, the role will automatically detect if community.docker.docker_compose_v2 +# is available and fall back to shell mode if needed # docker_deploy_shell: true docker_deploy_compose_template_backup: false -docker_deploy_stack_template_backup: false docker_deploy_folders_additional: [] docker_deploy_folders: "{{ docker_deploy_files + docker_deploy_templates + docker_deploy_git_repositories + docker_deploy_folders_additional }}" @@ -20,15 +20,11 @@ docker_deploy_git_repositories: [] docker_deploy_configs: [] docker_deploy_secrets: [] -docker_deploy_stack_pip_requirements: - - jsondiff - - pyyaml - # Can be used to forcefully add the '--force-recreate' to the docker-compose up -#docker_deploy_shell_start_default_additional_parameters: +#docker_deploy_shell_start_default_additional_parameters: -#docker_deploy_shell_start_default: docker-compose pull && docker-compose up -d +#docker_deploy_shell_start_default: docker compose pull && docker compose up -d # Declare helper docker services that can be used to generate helper files, like an helper Makefile -docker_deploy_services: "{{ ( ( (docker_deploy_templates + docker_deploy_files) | selectattr('service', 'defined') | map(attribute='service') | unique | list) + docker_deploy_services_additional ) | sort }}" +docker_deploy_services: "{{ (((docker_deploy_templates + docker_deploy_files) | selectattr('service', 'defined') | map(attribute='service') | unique | list) + docker_deploy_services_additional) | sort }}" docker_deploy_services_additional: [] diff --git a/docker-test.sh b/docker-test.sh new file mode 100755 index 0000000..af3898a --- /dev/null +++ b/docker-test.sh @@ -0,0 +1,97 @@ +#!/usr/bin/env bash +# +# Run tests in Docker containers for different Ansible versions +# + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Default values +ANSIBLE_VERSION="${1:-all}" +PYTHON_VERSION="${2:-3.11}" +TEST_TYPE="${3:-syntax}" + +# Function to run test for a specific version +run_test() { + local version=$1 + local python_ver=$2 + + echo -e "\n${BLUE}========================================${NC}" + echo -e "${BLUE}Testing Ansible ${version} with Python ${python_ver}${NC}" + echo -e "${BLUE}========================================${NC}" + + # Build the test image + echo -e "${YELLOW}Building test image...${NC}" + docker build \ + --build-arg ANSIBLE_VERSION="$version" \ + --build-arg PYTHON_VERSION="$python_ver" \ + -t ansible-docker-deploy-test:ansible-${version} \ + -f Dockerfile.test \ + . + + # Run the test + echo -e "${YELLOW}Running tests...${NC}" + case "$TEST_TYPE" in + syntax) + docker run --rm ansible-docker-deploy-test:ansible-${version} \ + ansible-playbook tests/test.yml -i tests/inventory --syntax-check + ;; + lint) + docker run --rm ansible-docker-deploy-test:ansible-${version} \ + sh -c "pip install yamllint ansible-lint && yamllint . && ansible-lint" + ;; + all) + docker run --rm \ + -v /var/run/docker.sock:/var/run/docker.sock \ + ansible-docker-deploy-test:ansible-${version} \ + sh -c "cd tests && ./run-tests.sh" + ;; + *) + docker run --rm ansible-docker-deploy-test:ansible-${version} \ + ansible-playbook "tests/${TEST_TYPE}.yml" -i tests/inventory -vv + ;; + esac + + if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ Ansible ${version} tests passed${NC}" + return 0 + else + echo -e "${RED}✗ Ansible ${version} tests failed${NC}" + return 1 + fi +} + +# Main execution +if [ "$ANSIBLE_VERSION" = "all" ]; then + echo -e "${GREEN}=== Running tests for all Ansible versions ===${NC}\n" + + VERSIONS=("5" "6" "7" "8" "9" "latest") + FAILED_TESTS=() + + for version in "${VERSIONS[@]}"; do + if ! run_test "$version" "$PYTHON_VERSION"; then + FAILED_TESTS+=("$version") + fi + done + + # Summary + echo -e "\n${GREEN}=== Test Summary ===${NC}" + if [ ${#FAILED_TESTS[@]} -eq 0 ]; then + echo -e "${GREEN}All tests passed!${NC}" + exit 0 + else + echo -e "${RED}Failed tests:${NC}" + for version in "${FAILED_TESTS[@]}"; do + echo -e "${RED} - Ansible $version${NC}" + done + exit 1 + fi +else + run_test "$ANSIBLE_VERSION" "$PYTHON_VERSION" +fi diff --git a/meta/main.yml b/meta/main.yml index fabddd4..2607c7c 100644 --- a/meta/main.yml +++ b/meta/main.yml @@ -1,13 +1,14 @@ galaxy_info: + role_name: ansible_docker_deploy + namespace: fccn author: Ivo Branco description: Deploy docker compose company: FCT|FCCN issue_tracker_url: https://github.com/fccn/ansible-docker-deploy/issues license: GPL-3.0-only - min_ansible_version: 2.7.12 - galaxy_tags: + min_ansible_version: "4.0" + galaxy_tags: - deploy - docker - docker-compose - - docker-stack dependencies: [] diff --git a/molecule/default/converge.yml b/molecule/default/converge.yml new file mode 100644 index 0000000..cd7f09e --- /dev/null +++ b/molecule/default/converge.yml @@ -0,0 +1,30 @@ +--- +- name: Converge + hosts: all + gather_facts: yes + become: yes + + vars: + test_deploy_folder: "/opt/test-app" + + pre_tasks: + - name: Update apt cache + apt: + update_cache: yes + cache_valid_time: 3600 + when: ansible_os_family == 'Debian' + + - name: Install Docker CLI and required packages + apt: + name: + - docker.io + - docker-compose-v2 + - python3-docker + state: present + when: ansible_os_family == 'Debian' + + roles: + - role: ansible-docker-deploy + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ playbook_dir }}/files/docker-compose.yml.j2" + docker_deploy_shell: true diff --git a/molecule/default/files/docker-compose.yml.j2 b/molecule/default/files/docker-compose.yml.j2 new file mode 100644 index 0000000..df1ae91 --- /dev/null +++ b/molecule/default/files/docker-compose.yml.j2 @@ -0,0 +1,7 @@ +version: '3.8' +services: + nginx: + image: nginx:alpine + container_name: molecule_test_nginx + ports: + - "8080:80" diff --git a/molecule/default/molecule.yml b/molecule/default/molecule.yml new file mode 100644 index 0000000..ffb8c98 --- /dev/null +++ b/molecule/default/molecule.yml @@ -0,0 +1,42 @@ +--- +dependency: + name: galaxy +driver: + name: docker +platforms: + - name: instance + image: geerlingguy/docker-ubuntu2204-ansible:latest + command: "" + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + - /var/run/docker.sock:/var/run/docker.sock + cgroupns_mode: host + privileged: true + pre_build_image: true +provisioner: + name: ansible + config_options: + defaults: + callbacks_enabled: profile_tasks,timer + stdout_callback: default + result_format: yaml + roles_path: ${MOLECULE_PROJECT_DIRECTORY}/.. + inventory: + host_vars: + instance: + ansible_user: root +verifier: + name: ansible +scenario: + test_sequence: + - dependency + - cleanup + - destroy + - syntax + - create + - prepare + - converge + - side_effect + - verify + - cleanup + - destroy diff --git a/molecule/default/prepare.yml b/molecule/default/prepare.yml new file mode 100644 index 0000000..17b806e --- /dev/null +++ b/molecule/default/prepare.yml @@ -0,0 +1,8 @@ +--- +- name: Prepare + hosts: all + gather_facts: no + tasks: + - name: Wait for system to be ready + wait_for_connection: + timeout: 300 diff --git a/molecule/default/verify.yml b/molecule/default/verify.yml new file mode 100644 index 0000000..017ee7b --- /dev/null +++ b/molecule/default/verify.yml @@ -0,0 +1,27 @@ +--- +- name: Verify + hosts: all + gather_facts: no + tasks: + - name: Check if docker-compose.yml was deployed + stat: + path: /opt/test-app/docker-compose.yml + register: compose_file + + - name: Verify compose file exists + assert: + that: + - compose_file.stat.exists + fail_msg: "docker-compose.yml was not deployed" + + - name: Check if container is running + docker_container_info: + name: molecule_test_nginx + register: container_info + + - name: Verify container is running + assert: + that: + - container_info.exists + - container_info.container.State.Running + fail_msg: "Container is not running" diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..64a2c9d --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,8 @@ +# Development requirements (includes test requirements) +-r requirements.txt + +# Additional development tools +pytest>=7.0.0 +pytest-ansible>=3.0.0 +black>=22.0.0 +flake8>=5.0.0 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1f4cbf8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +# Python requirements for development and testing +ansible>=4.0 +ansible-lint>=6.0.0 +yamllint>=1.26.0 +molecule>=5.0.0 +molecule-plugins[docker]>=23.0.0 +docker>=6.0.0 +jmespath>=1.0.0 + +# Note: Also install the community.docker collection: +# ansible-galaxy collection install community.docker diff --git a/requirements.yml b/requirements.yml new file mode 100644 index 0000000..acfdcde --- /dev/null +++ b/requirements.yml @@ -0,0 +1,5 @@ +--- +collections: + - name: community.docker + # Note: Version constraint removed to avoid Galaxy API issues with older Ansible versions + # Minimum version 3.0.0 is still recommended diff --git a/tasks/docker_clean.yml b/tasks/docker_clean.yml index a471c1f..b6f7a53 100644 --- a/tasks/docker_clean.yml +++ b/tasks/docker_clean.yml @@ -1,11 +1,11 @@ --- -- name: Delete old configs for this stack +- name: Delete old configs for this deployment shell: docker config ls --filter name={{ _docker_deploy_name }} --format {% raw %}'{{.ID}}'{% endraw %} | xargs docker config rm || true when: not ansible_check_mode changed_when: False tags: docker_deploy -- name: Delete old secrets for this stack +- name: Delete old secrets for this deployment shell: docker secret ls --filter name={{ _docker_deploy_name }} --format {% raw %}'{{.ID}}'{% endraw %} | xargs docker secret rm || true when: not ansible_check_mode changed_when: False diff --git a/tasks/docker_configs.yml b/tasks/docker_configs.yml index 365cf37..ed8d7e4 100644 --- a/tasks/docker_configs.yml +++ b/tasks/docker_configs.yml @@ -3,7 +3,7 @@ stat: path: "{{ item.dest }}" when: item.config_name is defined - with_items: "{{ ( docker_deploy_files | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_files }}" + with_items: "{{ (docker_deploy_files | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_files }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_files_stat_out @@ -21,15 +21,15 @@ label: "{{ item.0.dest }}" when: item.0.config_name is defined and ( item.0.when | default(true) | bool ) with_together: - - "{{ docker_deploy_files | default( [] ) }}" - - "{{ docker_deploy_files_stat_out.results | default( [] ) }}" + - "{{ docker_deploy_files | default([]) }}" + - "{{ docker_deploy_files_stat_out.results | default([]) }}" tags: docker_deploy - name: Get checksum for each templated file with a config_name defined stat: path: "{{ item.dest }}" when: item.config_name is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_templates | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_templates }}" + with_items: "{{ (docker_deploy_templates | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_templates }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_templates_stat_out @@ -42,8 +42,8 @@ label: "{{ item.0.dest }}" when: item.0.config_name is defined and ( item.0.when | default(true) | bool ) with_together: - - "{{ docker_deploy_templates | default( [] ) }}" - - "{{ docker_deploy_templates_stat_out.results | default( [] ) }}" + - "{{ docker_deploy_templates | default([]) }}" + - "{{ docker_deploy_templates_stat_out.results | default([]) }}" tags: docker_deploy - name: Deploy docker configs diff --git a/tasks/docker_deploy_compose.yml b/tasks/docker_deploy_compose.yml index c69a6d3..135fa1a 100644 --- a/tasks/docker_deploy_compose.yml +++ b/tasks/docker_deploy_compose.yml @@ -9,28 +9,29 @@ - name: Stop docker containers and remove its volumes # Do not change this deprecated name to 'docker_compose' so we can still be compatible with ansible 2.7 - docker_service: + community.docker.docker_compose_v2: project_src: "{{ docker_deploy_base_folder }}" state: absent remove_volumes: true when: docker_deploy_force_remove_volumes | default(false) tags: docker_deploy -- name: Start docker containers +- name: Start docker containers using docker_compose_v2 community module # Do not change this deprecated name to 'docker_compose' so we can still be compatible with ansible 2.7 - docker_service: + community.docker.docker_compose_v2: project_src: "{{ docker_deploy_base_folder }}" services: "{{ limited_services.split(',') if limited_services is defined else omit }}" - # restart all containers if anything has changed - restarted: "{{ (docker_deploy_force_restart | default(false)) or docker_compose_template_out.changed or docker_deploy_files_out.changed or docker_deploy_templates_out.changed or docker_deploy_git_repositories_out.changed }}" - pull: true # upgrade images prior to starting the application - build: true # always build images prior to starting the application - #recreate: always + # Use 'present' state which will create/update containers as needed. The 'recreate' parameter controls whether to recreate on changes. + state: present + pull: "{{ docker_deploy_pull | default(omit) }}" + build: "{{ docker_deploy_build | default(omit) }}" + wait: true # wait for containers to be running/healthy + recreate: "{{ 'always' if (docker_deploy_force_restart | default(false)) or docker_compose_template_out.changed or docker_deploy_files_out.changed or docker_deploy_templates_out.changed or docker_deploy_git_repositories_out.changed else docker_deploy_recreate | default(omit) }}" register: docker_deploy_output tags: docker_deploy - name: HealthCheck include_tasks: docker_healthcheck.yml - tags: + tags: - docker_deploy - healthcheck diff --git a/tasks/docker_deploy_shell.yml b/tasks/docker_deploy_shell.yml index 9b56cef..4632eb5 100644 --- a/tasks/docker_deploy_shell.yml +++ b/tasks/docker_deploy_shell.yml @@ -13,43 +13,28 @@ tags: docker_deploy - name: Pull and build images before stopping and starting - shell: docker-compose pull && docker-compose build + shell: docker compose pull && docker compose build args: chdir: "{{ docker_deploy_base_folder }}" - when: docker_deploy_shell_start is defined or ( docker_deploy_shell | default (false) | bool ) + when: docker_deploy_shell_start is defined or (docker_deploy_shell | default(false) | bool) tags: docker_deploy -- name: Stop service using shell command +- name: Stop service using shell command # noqa: command-instead-of-shell shell: "{{ docker_deploy_shell_stop }}" args: chdir: "{{ docker_deploy_base_folder }}" when: docker_deploy_shell_stop is defined tags: docker_deploy -- name: Start service using shell command - shell: "{{ docker_deploy_shell_start if docker_deploy_shell_start is defined else ( - docker_deploy_shell_start_default if docker_deploy_shell_start_default is defined else ( - 'docker-compose up -d ' + - (docker_deploy_shell_start_default_additional_parameters | - default ( - (docker_deploy_shell_start_default_additional_parameters_if_changed | default('')) - if (docker_deploy_force_restart | default(false)) or - (docker_compose_template_out is defined and docker_compose_template_out.changed) or - docker_deploy_files_out.changed or - docker_deploy_templates_out.changed or - docker_deploy_git_repositories_out.changed - else '' - ) - ) - ) - ) }}" +- name: Start service using shell command # noqa: command-instead-of-shell + shell: "{{ docker_deploy_shell_start if docker_deploy_shell_start is defined else (docker_deploy_shell_start_default if docker_deploy_shell_start_default is defined else ('docker compose up -d ' + (docker_deploy_shell_start_default_additional_parameters | default((docker_deploy_shell_start_default_additional_parameters_if_changed | default('')) if (docker_deploy_force_restart | default(false)) or (docker_compose_template_out is defined and docker_compose_template_out.changed) or docker_deploy_files_out.changed or docker_deploy_templates_out.changed or docker_deploy_git_repositories_out.changed else '')))) }}" args: chdir: "{{ docker_deploy_base_folder }}" - when: docker_deploy_shell_start is defined or ( docker_deploy_shell | default (false) | bool ) + when: docker_deploy_shell_start is defined or (docker_deploy_shell | default(false) | bool) tags: docker_deploy - name: HealthCheck include_tasks: docker_healthcheck.yml - tags: + tags: - docker_deploy - healthcheck diff --git a/tasks/docker_deploy_stack.yml b/tasks/docker_deploy_stack.yml deleted file mode 100644 index 82e3577..0000000 --- a/tasks/docker_deploy_stack.yml +++ /dev/null @@ -1,70 +0,0 @@ ---- -- name: Template docker stack - template: - dest: "{{ docker_deploy_base_folder }}/docker-stack.yml" - src: "{{ docker_deploy_stack_template }}" - backup: "{{ docker_deploy_stack_template_backup }}" - tags: docker_deploy - -- name: Install docker_stack ansible module requirements - pip: - name: "{{ docker_deploy_stack_pip_requirements }}" - tags: docker_deploy - -- name: Define docker stack state and name - set_fact: - _docker_deploy_stack_state: "{{ docker_deploy_stack_state | default('present') }}" - docker_deploy_stack_state__message: "??" - tags: always - -- name: Define message if starting - set_fact: - docker_deploy_stack_state__message: "{{ 'Start' }}" - when: _docker_deploy_stack_state == 'present' - tags: always - -- name: Define message if stopping - set_fact: - docker_deploy_stack_state__message: "{{ 'Stopping' }}" - no_log: True - when: _docker_deploy_stack_state == 'absent' - tags: always - -- name: "Start docker stack" - shell: docker stack deploy {{ _docker_deploy_name }}{{ ' --prune' if docker_deploy_stack_prune is defined and docker_deploy_stack_prune else '' }} --compose-file "{{ docker_deploy_base_folder }}/docker-stack.yml" - when: _docker_deploy_stack_state == 'present' - # retry the deploy of the stack, because sometimes it raises some strange errors that a new deploy fixes. - register: result_start - until: result_start.rc == 0 - retries: 5 - delay: 10 - ignore_errors: "{{ ansible_check_mode }}" - tags: docker_deploy - -- name: "Stop docker stack" - shell: docker stack rm {{ _docker_deploy_name }} - when: _docker_deploy_stack_state == 'absent' - register: result_stop - until: result_stop.rc == 0 - retries: 5 - delay: 10 - ignore_errors: "{{ ansible_check_mode }}" - tags: docker_deploy - -- name: Pause for {{ docker_deploy_stack_pause_to_verify | default(15) }} seconds so previous version of the stack could stop - pause: - seconds: "{{ docker_deploy_stack_pause_to_verify | default(15) }}" - tags: docker_deploy - -- name: HealthCheck - shell: docker stack ps {{ _docker_deploy_name }} | tail -n +2 | grep -v " \\\\_ " | egrep -v "[_-]job" | awk '{ if ( $5 != $6 ) {exit -1} }' - retries: "{{ docker_deploy_stack_verify_retries | default(50) }}" - delay: "{{ docker_deploy_stack_verify_delay | default(15) }}" - register: result_healthcheck - until: result_healthcheck.rc == 0 - when: not ansible_check_mode and _docker_deploy_stack_state == 'present' - changed_when: False - ignore_errors: "{{ ansible_check_mode }}" - tags: - - docker_deploy - - healthcheck diff --git a/tasks/docker_healthcheck.yml b/tasks/docker_healthcheck.yml index 5febf7d..1e4b7a9 100644 --- a/tasks/docker_healthcheck.yml +++ b/tasks/docker_healthcheck.yml @@ -7,6 +7,6 @@ delay: "{{ docker_deploy_healthcheck_delay | default(omit) }}" when: ( docker_deploy_shell_start is defined or docker_deploy_compose_template is defined ) and ( docker_deploy_healthcheck | default(true) ) changed_when: false # shell command don't change anything on the server - tags: + tags: - docker_deploy - healthcheck diff --git a/tasks/docker_secrets.yml b/tasks/docker_secrets.yml index 3065774..aece2a1 100644 --- a/tasks/docker_secrets.yml +++ b/tasks/docker_secrets.yml @@ -3,7 +3,7 @@ stat: path: "{{ item.dest }}" when: item.secret_name is defined - with_items: "{{ ( docker_deploy_files | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_files }}" + with_items: "{{ (docker_deploy_files | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_files }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_files_stat_out @@ -21,15 +21,15 @@ label: "{{ item.0.dest }}" when: item.0.secret_name is defined and ( item.0.when | default(true) | bool ) with_together: - - "{{ docker_deploy_files | default( [] ) }}" - - "{{ docker_deploy_files_stat_out.results | default( [] ) }}" + - "{{ docker_deploy_files | default([]) }}" + - "{{ docker_deploy_files_stat_out.results | default([]) }}" tags: docker_deploy - name: Get checksum for each templated file with a secret_name defined stat: path: "{{ item.dest }}" when: item.secret_name is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_templates | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_templates }}" + with_items: "{{ (docker_deploy_templates | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_templates }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_templates_stat_out @@ -42,8 +42,8 @@ label: "{{ item.0.dest }}" when: item.0.secret_name is defined and ( item.0.when | default(true) | bool ) with_together: - - "{{ docker_deploy_templates | default( [] ) }}" - - "{{ docker_deploy_templates_stat_out.results | default( [] ) }}" + - "{{ docker_deploy_templates | default([]) }}" + - "{{ docker_deploy_templates_stat_out.results | default([]) }}" tags: docker_deploy - name: Deploy docker secrets diff --git a/tasks/git.yml b/tasks/git.yml index 4b61eaa..4c4054d 100644 --- a/tasks/git.yml +++ b/tasks/git.yml @@ -1,6 +1,6 @@ --- - name: Install git - package: + package: name: git state: present when: docker_deploy_git_repositories is defined and ( docker_deploy_git_repositories | length ) > 0 @@ -17,16 +17,16 @@ tags: docker_deploy - name: Update git repository source code - git: + git: repo: "{{ item.repo }}" dest: "{{ item.dest }}" force: "{{ item.force | default(omit) }}" version: "{{ item.version | default(omit) }}" accept_hostkey: yes - key_file: "{{ ( item.dest + 'ssh_key' ) if item.ssh_key is defined else omit }}" + key_file: "{{ (item.dest + 'ssh_key') if item.ssh_key is defined else omit }}" loop_control: label: "{{ item.repo }}" - with_items: "{{ ( docker_deploy_git_repositories | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_git_repositories }}" + with_items: "{{ (docker_deploy_git_repositories | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_git_repositories }}" when: docker_deploy_git_repositories is defined register: docker_deploy_git_repositories_out tags: docker_deploy @@ -45,7 +45,7 @@ path: "{{ item.dest }}" state: directory owner: "{{ item.owner }}" - group: "{{ item.group }}" + group: "{{ item.group }}" mode: "{{ item.mode }}" recurse: yes loop_control: @@ -61,6 +61,6 @@ label: "{{ item.0.dest }}" when: item.0.fact is defined with_together: - - "{{ docker_deploy_git_repositories | default( [] ) }}" - - "{{ docker_deploy_git_repositories_out.results | default( [] ) }}" + - "{{ docker_deploy_git_repositories | default([]) }}" + - "{{ docker_deploy_git_repositories_out.results | default([]) }}" tags: docker_deploy diff --git a/tasks/main.yml b/tasks/main.yml index b64702f..0a05425 100644 --- a/tasks/main.yml +++ b/tasks/main.yml @@ -1,15 +1,14 @@ --- - name: Verify presence of variables fail: - msg: You need to define at least one of 'docker_deploy_stack_template', 'docker_deploy_compose_template' or 'docker_deploy_shell_start' variable. - when: docker_deploy_stack_template is not defined - and docker_deploy_compose_template is not defined + msg: You need to define at least one of 'docker_deploy_compose_template' or 'docker_deploy_shell_start' variable. + when: docker_deploy_compose_template is not defined and docker_deploy_shell_start is not defined tags: always -- name: Define docker deploy name variable from the docker_deploy_stack_name or from the basename of docker_deploy_base_folder folder +- name: Define docker deploy name variable from the basename of docker_deploy_base_folder folder set_fact: - _docker_deploy_name: "{{ docker_deploy_stack_name | default(docker_deploy_base_folder | basename) }}" + _docker_deploy_name: "{{ docker_deploy_base_folder | basename }}" tags: always - name: Print the docker deploy name @@ -30,8 +29,8 @@ - name: Create folders file: dest: "{{ item.dest | dirname }}" - owner: "{{ item.dir_owner|default(omit) }}" - group: "{{ item.dir_group|default(omit) }}" + owner: "{{ item.dir_owner | default(omit) }}" + group: "{{ item.dir_group | default(omit) }}" mode: "{{ item.dir_mode | default(omit) }}" recurse: true state: directory @@ -49,7 +48,7 @@ owner: "{{ item.owner | default('root') }}" group: "{{ item.group | default('root') }}" when: item.src is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_files | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_files }}" + with_items: "{{ (docker_deploy_files | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_files }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_files_out @@ -69,7 +68,7 @@ group: "{{ item.group | default('root') }}" backup: "{{ item.backup | default(omit) }}" when: item.src is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_templates | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_templates }}" + with_items: "{{ (docker_deploy_templates | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_templates }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_templates_out @@ -84,7 +83,7 @@ group: "{{ item.group | default('root') }}" backup: "{{ item.backup | default(omit) }}" when: item.src_data is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_templates | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_templates }}" + with_items: "{{ (docker_deploy_templates | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_templates }}" loop_control: label: "{{ item.dest }}" tags: docker_deploy @@ -101,10 +100,38 @@ include_tasks: stop_old.yml tags: docker_deploy +- name: Check if community.docker.docker_compose_v2 module is available # noqa: key-order[task] + block: + - name: Try to load docker_compose_v2 module info + ansible.builtin.command: ansible-doc -t module community.docker.docker_compose_v2 + register: docker_compose_v2_check + changed_when: false + failed_when: false + delegate_to: localhost + become: false + run_once: true + + - name: Auto-enable shell mode if docker_compose_v2 not available and user hasn't explicitly set docker_deploy_shell + set_fact: + docker_deploy_shell: true + when: + - docker_deploy_shell is not defined or not docker_deploy_shell + - docker_compose_v2_check.rc != 0 + - docker_deploy_compose_template is defined + + - name: Warn about falling back to shell mode + debug: + msg: "Warning: community.docker.docker_compose_v2 module not available. Automatically using shell mode for deployment." + when: + - docker_compose_v2_check.rc != 0 + - docker_deploy_compose_template is defined + when: docker_deploy_compose_template is defined and ( docker_deploy_shell is not defined or not docker_deploy_shell ) + tags: docker_deploy + - name: Deploy docker using shell directly include_tasks: docker_deploy_shell.yml when: docker_deploy_shell_start is defined or docker_deploy_shell_stop is defined or ( docker_deploy_shell | default (false) | bool ) - tags: + tags: - docker_deploy - healthcheck @@ -113,10 +140,5 @@ when: docker_deploy_compose_template is defined and not ( docker_deploy_shell | default (false) | bool ) tags: docker_deploy -- name: Deploy docker stack to swarm - include_tasks: docker_deploy_stack.yml - when: docker_deploy_stack_template is defined - tags: docker_deploy - - include_tasks: docker_clean.yml tags: docker_deploy diff --git a/tasks/s3.yml b/tasks/s3.yml index dafed01..70e09b4 100644 --- a/tasks/s3.yml +++ b/tasks/s3.yml @@ -5,15 +5,15 @@ state: present tags: docker_deploy -- name: Download file from S3 - shell: "{{ s3cmd_prefix }} {{ item.src if item.src.startswith('s3://') else 's3://' + docker_deploy_s3_bucket + ( '' if item.src.startswith('/') else '/' ) + item.src }} {{ item.dest }}" +- name: Download file from S3 # noqa: command-instead-of-shell + shell: "{{ s3cmd_prefix }} {{ item.src if item.src.startswith('s3://') else 's3://' + docker_deploy_s3_bucket + ('' if item.src.startswith('/') else '/') + item.src }} {{ item.dest }}" vars: s3cmd_prefix: s3cmd get --force {{ '--host ' + docker_deploy_s3_host + ' --host-bucket ' + docker_deploy_s3_bucket }} environment: AWS_ACCESS_KEY_ID: "{{ docker_deploy_s3_access_key_id }}" AWS_SECRET_ACCESS_KEY: "{{ docker_deploy_s3_secret_access_key }}" when: item.src is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_s3_files | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_s3_files }}" + with_items: "{{ (docker_deploy_s3_files | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_s3_files }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_s3_out @@ -26,7 +26,7 @@ owner: "{{ item.owner | default('root') }}" group: "{{ item.group | default('root') }}" when: item.src is defined and ( item.when | default(true) | bool ) - with_items: "{{ ( docker_deploy_s3_files | selectattr('service', 'in', limited_services.split(',') ) ) if limited_services is defined else docker_deploy_s3_files }}" + with_items: "{{ (docker_deploy_s3_files | selectattr('service', 'in', limited_services.split(','))) if limited_services is defined else docker_deploy_s3_files }}" loop_control: label: "{{ item.dest }}" register: docker_deploy_s3_permissions_out diff --git a/tasks/stop_old.yml b/tasks/stop_old.yml index 3531cea..dab4c29 100644 --- a/tasks/stop_old.yml +++ b/tasks/stop_old.yml @@ -1,12 +1,12 @@ --- - name: Stop and remove old docker containers - docker_container: + docker_container: name: "{{ item }}" state: absent with_items: "{{ docker_containers_to_remove | default([]) }}" tags: docker_deploy -- name: Stop and remove old docker services +- name: Stop and remove old docker services # noqa: command-instead-of-shell shell: docker service rm {{ item }} with_items: "{{ docker_services_to_remove | default([]) }}" tags: docker_deploy diff --git a/templates/_docker_deploy_helper.j2 b/templates/_docker_deploy_helper.j2 index d5d2409..8e4ae81 100644 --- a/templates/_docker_deploy_helper.j2 +++ b/templates/_docker_deploy_helper.j2 @@ -4,7 +4,7 @@ ## -## Prints the configs of a `service`. +## Prints the configs of a `service`. ## The `service` is an optional parameter, if not defined it will render all templates and ## files with the attribute `config_name` defined. Example: ## @@ -27,7 +27,7 @@ {% else %} {% set templates_and_files = (templates_and_files | selectattr('config_name', 'defined') | list) %} {% endif %} -{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + +{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + (templates_and_files | selectattr('when', 'defined') | selectattr('when', 'equalto', true) | list) %} {% if ( (templates_and_files | length > 0) and header ) %} configs: @@ -39,7 +39,7 @@ {% endmacro %} -## Prints the secrets of a `service`. +## Prints the secrets of a `service`. ## The `service` is an optional parameter, if not defined it will render all templates and ## files with the attribute `secret_name` defined. Example: ## @@ -62,7 +62,7 @@ {% else %} {% set templates_and_files = (templates_and_files | selectattr('secret_name', 'defined') | list) %} {% endif %} -{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + +{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + (templates_and_files | selectattr('when', 'defined') | selectattr('when', 'equalto', true) | list) %} {% if ( (templates_and_files | length > 0) and header ) %} secrets: @@ -74,7 +74,7 @@ {% endmacro %} -## Prints the configs of a docker stack. +## Prints the configs of a docker compose. ## ## Configuration: ## docker_deploy_templates: @@ -90,7 +90,7 @@ {% macro configs(header=true) %} {% set templates_and_files = (docker_deploy_templates + docker_deploy_files) %} {% set templates_and_files = (templates_and_files | selectattr('config_name', 'defined') | list) %} -{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + +{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + (templates_and_files | selectattr('when', 'defined') | selectattr('when', 'equalto', true) | list) %} {% if ( (templates_and_files | length > 0) and header ) %} configs: @@ -102,7 +102,7 @@ configs: {% endmacro %} -## Prints the secrets of a docker stack. +## Prints the secrets of a docker compose. ## ## Configuration: ## docker_deploy_files: @@ -118,7 +118,7 @@ configs: {% macro secrets(header=true) %} {% set templates_and_files = (docker_deploy_templates + docker_deploy_files) %} {% set templates_and_files = (templates_and_files | selectattr('secret_name', 'defined') | list) %} -{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + +{% set templates_and_files = (templates_and_files | rejectattr('when', 'defined') | list) + (templates_and_files | selectattr('when', 'defined') | selectattr('when', 'equalto', true) | list) %} {% if ( (templates_and_files | length > 0) and header ) %} secrets: diff --git a/tests/run-tests.sh b/tests/run-tests.sh new file mode 100755 index 0000000..5342811 --- /dev/null +++ b/tests/run-tests.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# +# Test runner script for ansible-docker-deploy role +# + +set -e + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Script directory +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_DIR="$(dirname "$SCRIPT_DIR")" + +echo -e "${GREEN}=== Ansible Docker Deploy - Test Suite ===${NC}\n" + +# Setup +echo "Setting up test environment..." +cd "$PROJECT_DIR" + +# Run tests using Makefile +echo -e "${YELLOW}Running all tests...${NC}\n" + +if make test; then + echo -e "\n${GREEN}=== All tests passed! ===${NC}" + exit 0 +else + echo -e "\n${RED}=== Tests failed ===${NC}" + exit 1 +fi diff --git a/tests/test-compose-v2.yml b/tests/test-compose-v2.yml new file mode 100644 index 0000000..919d5d3 --- /dev/null +++ b/tests/test-compose-v2.yml @@ -0,0 +1,89 @@ +--- +- hosts: localhost + connection: local + gather_facts: yes + + vars: + test_base_folder: "/tmp/ansible-docker-deploy-test-v2" + test_deploy_folder: "{{ test_base_folder }}/test-app" + + tasks: + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + tags: cleanup + + - name: Create test directory + file: + path: "{{ test_base_folder }}" + state: directory + mode: '0755' + + - name: Create index.html template for testing + copy: + dest: "{{ test_base_folder }}/index.html.j2" + content: | + + +

Ansible Docker Deploy Test (docker_compose_v2 mode) - Success!

+ + + + - name: Create test docker-compose template + copy: + dest: "{{ test_base_folder }}/docker-compose.yml.j2" + content: | + version: '3.8' + services: + nginx: + image: nginx:alpine + container_name: test_nginx_v2 + ports: + - "18080:80" + volumes: + - {{ test_deploy_folder }}/index.html:/usr/share/nginx/html/index.html:ro + + - name: Test basic deployment with docker_compose_v2 module + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ test_base_folder }}/docker-compose.yml.j2" + # docker_deploy_shell is NOT set, so it will use docker_compose_v2 module + docker_deploy_templates: + - src: "{{ test_base_folder }}/index.html.j2" + dest: "{{ test_deploy_folder }}/index.html" + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + + - name: Wait for container to be healthy + wait_for: + port: 18080 + delay: 5 + timeout: 30 + + - name: Test HTTP response + uri: + url: http://localhost:18080 + return_content: yes + register: response + failed_when: "'Success!' not in response.content" + + - name: Stop test container + docker_container: + name: test_nginx_v2 + state: stopped + ignore_errors: yes + + - name: Remove test container + docker_container: + name: test_nginx_v2 + state: absent + ignore_errors: yes + + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + tags: cleanup diff --git a/tests/test-compose.yml b/tests/test-compose.yml new file mode 100644 index 0000000..146d71a --- /dev/null +++ b/tests/test-compose.yml @@ -0,0 +1,89 @@ +--- +- hosts: localhost + connection: local + gather_facts: yes + + vars: + test_base_folder: "/tmp/ansible-docker-deploy-test" + test_deploy_folder: "{{ test_base_folder }}/test-app" + + tasks: + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + tags: cleanup + + - name: Create test directory + file: + path: "{{ test_base_folder }}" + state: directory + mode: '0755' + + - name: Create index.html template for testing + copy: + dest: "{{ test_base_folder }}/index.html.j2" + content: | + + +

Ansible Docker Deploy Test - Success!

+ + + + - name: Create test docker-compose template + copy: + dest: "{{ test_base_folder }}/docker-compose.yml.j2" + content: | + version: '3.8' + services: + nginx: + image: nginx:alpine + container_name: test_nginx + ports: + - "8080:80" + volumes: + - {{ test_deploy_folder }}/index.html:/usr/share/nginx/html/index.html:ro + + - name: Test basic deployment with compose + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ test_base_folder }}/docker-compose.yml.j2" + docker_deploy_shell: true + docker_deploy_templates: + - src: "{{ test_base_folder }}/index.html.j2" + dest: "{{ test_deploy_folder }}/index.html" + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + + - name: Wait for container to be healthy + wait_for: + port: 8080 + delay: 5 + timeout: 30 + + - name: Test HTTP response + uri: + url: http://localhost:8080 + return_content: yes + register: response + failed_when: "'Success!' not in response.content" + + - name: Stop test container + docker_container: + name: test_nginx + state: stopped + ignore_errors: yes + + - name: Remove test container + docker_container: + name: test_nginx + state: absent + ignore_errors: yes + + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + tags: cleanup diff --git a/tests/test-files-templates-v2.yml b/tests/test-files-templates-v2.yml new file mode 100644 index 0000000..7ec9aee --- /dev/null +++ b/tests/test-files-templates-v2.yml @@ -0,0 +1,89 @@ +--- +- hosts: localhost + connection: local + gather_facts: yes + + vars: + test_base_folder: "/tmp/ansible-docker-deploy-test-files-v2" + test_deploy_folder: "{{ test_base_folder }}/test-app" + + tasks: + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + + - name: Create test directory + file: + path: "{{ test_base_folder }}" + state: directory + mode: '0755' + + - name: Create test source file + copy: + dest: "{{ test_base_folder }}/test-config.txt" + content: "Test configuration file (docker_compose_v2 mode)" + + - name: Create test template + copy: + dest: "{{ test_base_folder }}/test-template.j2" + content: | + # Generated configuration (docker_compose_v2 mode) + hostname: {{ ansible_hostname }} + date: {{ ansible_date_time.iso8601 }} + + - name: Create minimal docker-compose template + copy: + dest: "{{ test_base_folder }}/docker-compose.yml.j2" + content: | + version: '3.8' + services: + busybox: + image: busybox:latest + container_name: test_busybox_v2 + command: sleep 30 + + - name: Test deployment with files and templates using docker_compose_v2 + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ test_base_folder }}/docker-compose.yml.j2" + # docker_deploy_shell is NOT set, so it will use docker_compose_v2 module + docker_deploy_files: + - src: "{{ test_base_folder }}/test-config.txt" + dest: "{{ test_deploy_folder }}/config.txt" + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + docker_deploy_templates: + - src: "{{ test_base_folder }}/test-template.j2" + dest: "{{ test_deploy_folder }}/rendered-config.txt" + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + + - name: Verify copied file exists + stat: + path: "{{ test_deploy_folder }}/config.txt" + register: copied_file + failed_when: not copied_file.stat.exists + + - name: Verify templated file exists + stat: + path: "{{ test_deploy_folder }}/rendered-config.txt" + register: templated_file + failed_when: not templated_file.stat.exists + + - name: Verify templated file content + shell: grep -q "hostname:" "{{ test_deploy_folder }}/rendered-config.txt" + changed_when: false + + - name: Stop and remove test container + docker_container: + name: test_busybox_v2 + state: absent + ignore_errors: yes + + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent diff --git a/tests/test-files-templates.yml b/tests/test-files-templates.yml new file mode 100644 index 0000000..c4e21bc --- /dev/null +++ b/tests/test-files-templates.yml @@ -0,0 +1,89 @@ +--- +- hosts: localhost + connection: local + gather_facts: yes + + vars: + test_base_folder: "/tmp/ansible-docker-deploy-test-files" + test_deploy_folder: "{{ test_base_folder }}/test-app" + + tasks: + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + + - name: Create test directory + file: + path: "{{ test_base_folder }}" + state: directory + mode: '0755' + + - name: Create test source file + copy: + dest: "{{ test_base_folder }}/test-config.txt" + content: "Test configuration file" + + - name: Create test template + copy: + dest: "{{ test_base_folder }}/test-template.j2" + content: | + # Generated configuration + hostname: {{ ansible_hostname }} + date: {{ ansible_date_time.iso8601 }} + + - name: Create minimal docker-compose template + copy: + dest: "{{ test_base_folder }}/docker-compose.yml.j2" + content: | + version: '3.8' + services: + busybox: + image: busybox:latest + container_name: test_busybox + command: sleep 30 + + - name: Test deployment with files and templates + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ test_base_folder }}/docker-compose.yml.j2" + docker_deploy_shell: true + docker_deploy_files: + - src: "{{ test_base_folder }}/test-config.txt" + dest: "{{ test_deploy_folder }}/config.txt" + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + docker_deploy_templates: + - src: "{{ test_base_folder }}/test-template.j2" + dest: "{{ test_deploy_folder }}/rendered-config.txt" + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + + - name: Verify copied file exists + stat: + path: "{{ test_deploy_folder }}/config.txt" + register: copied_file + failed_when: not copied_file.stat.exists + + - name: Verify templated file exists + stat: + path: "{{ test_deploy_folder }}/rendered-config.txt" + register: templated_file + failed_when: not templated_file.stat.exists + + - name: Verify templated file content + shell: grep -q "hostname:" "{{ test_deploy_folder }}/rendered-config.txt" + changed_when: false + + - name: Stop and remove test container + docker_container: + name: test_busybox + state: absent + ignore_errors: yes + + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent diff --git a/tests/test-secrets-configs-v2.yml b/tests/test-secrets-configs-v2.yml new file mode 100644 index 0000000..8307578 --- /dev/null +++ b/tests/test-secrets-configs-v2.yml @@ -0,0 +1,121 @@ +--- +- hosts: localhost + connection: local + gather_facts: yes + + vars: + test_base_folder: "/tmp/ansible-docker-deploy-test-secrets-v2" + test_deploy_folder: "{{ test_base_folder }}/test-app" + test_secret_value: "my-secret-password-v2-123" + test_config_value: "app.config=production-v2" + + tasks: + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + + - name: Create test directory + file: + path: "{{ test_base_folder }}" + state: directory + mode: '0755' + + - name: Create simple docker-compose template + copy: + dest: "{{ test_base_folder }}/docker-compose.yml.j2" + content: | + version: '3.8' + services: + alpine: + image: alpine:latest + container_name: test_alpine_secrets_v2 + command: sleep 30 + + - name: Test deployment with secrets and configs using docker_compose_v2 + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ test_base_folder }}/docker-compose.yml.j2" + # docker_deploy_shell is NOT set, so it will use docker_compose_v2 module + docker_deploy_templates: + - src_data: "{{ test_secret_value }}" + dest: "{{ test_deploy_folder }}/secret-data" + secret_name: test_secret + docker_target: /run/secrets/app-secret + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + - src_data: "{{ test_config_value }}" + dest: "{{ test_deploy_folder }}/config-data" + config_name: test_config + docker_target: /config/app.conf + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + + - name: Verify secret file was created + stat: + path: "{{ test_deploy_folder }}/secret-data" + register: secret_file + failed_when: not secret_file.stat.exists + + - name: Verify config file was created + stat: + path: "{{ test_deploy_folder }}/config-data" + register: config_file + failed_when: not config_file.stat.exists + + - name: Verify secret file content + command: cat "{{ test_deploy_folder }}/secret-data" + register: secret_content + changed_when: false + + - name: Verify config file content + command: cat "{{ test_deploy_folder }}/config-data" + register: config_content + changed_when: false + + - name: Assert secret content is correct + assert: + that: + - secret_content.stdout == test_secret_value + fail_msg: "Secret content does not match expected value" + + - name: Assert config content is correct + assert: + that: + - config_content.stdout == test_config_value + fail_msg: "Config content does not match expected value" + + - name: Verify checksum facts were created + assert: + that: + - docker_deploy_secrets_checksum is defined + - docker_deploy_configs_checksum is defined + - "'test-app_test_secret' in docker_deploy_secrets_checksum" + - "'test-app_test_config' in docker_deploy_configs_checksum" + fail_msg: "Checksum facts were not properly created" + + - name: Display checksum facts for verification + debug: + msg: + - "Secret checksums: {{ docker_deploy_secrets_checksum }}" + - "Config checksums: {{ docker_deploy_configs_checksum }}" + + - name: Verify secret checksum is a valid SHA hash + assert: + that: + - docker_deploy_secrets_checksum['test-app_test_secret'] | length == 10 + - docker_deploy_configs_checksum['test-app_test_config'] | length == 10 + fail_msg: "Checksums are not the expected length" + + - name: Stop and remove test container + docker_container: + name: test_alpine_secrets_v2 + state: absent + ignore_errors: yes + + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent diff --git a/tests/test-secrets-configs.yml b/tests/test-secrets-configs.yml new file mode 100644 index 0000000..2379cc4 --- /dev/null +++ b/tests/test-secrets-configs.yml @@ -0,0 +1,121 @@ +--- +- hosts: localhost + connection: local + gather_facts: yes + + vars: + test_base_folder: "/tmp/ansible-docker-deploy-test-secrets" + test_deploy_folder: "{{ test_base_folder }}/test-app" + test_secret_value: "my-secret-password-123" + test_config_value: "app.config=production" + + tasks: + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent + + - name: Create test directory + file: + path: "{{ test_base_folder }}" + state: directory + mode: '0755' + + - name: Create simple docker-compose template + copy: + dest: "{{ test_base_folder }}/docker-compose.yml.j2" + content: | + version: '3.8' + services: + alpine: + image: alpine:latest + container_name: test_alpine_secrets + command: sleep 30 + + - name: Test deployment with secrets and configs + include_role: + name: ansible-docker-deploy + vars: + docker_deploy_base_folder: "{{ test_deploy_folder }}" + docker_deploy_compose_template: "{{ test_base_folder }}/docker-compose.yml.j2" + docker_deploy_shell: true + docker_deploy_templates: + - src_data: "{{ test_secret_value }}" + dest: "{{ test_deploy_folder }}/secret-data" + secret_name: test_secret + docker_target: /run/secrets/app-secret + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + - src_data: "{{ test_config_value }}" + dest: "{{ test_deploy_folder }}/config-data" + config_name: test_config + docker_target: /config/app.conf + owner: "{{ ansible_user_id }}" + group: "{{ ansible_user_id }}" + + - name: Verify secret file was created + stat: + path: "{{ test_deploy_folder }}/secret-data" + register: secret_file + failed_when: not secret_file.stat.exists + + - name: Verify config file was created + stat: + path: "{{ test_deploy_folder }}/config-data" + register: config_file + failed_when: not config_file.stat.exists + + - name: Verify secret file content + command: cat "{{ test_deploy_folder }}/secret-data" + register: secret_content + changed_when: false + + - name: Verify config file content + command: cat "{{ test_deploy_folder }}/config-data" + register: config_content + changed_when: false + + - name: Assert secret content is correct + assert: + that: + - secret_content.stdout == test_secret_value + fail_msg: "Secret content does not match expected value" + + - name: Assert config content is correct + assert: + that: + - config_content.stdout == test_config_value + fail_msg: "Config content does not match expected value" + + - name: Verify checksum facts were created + assert: + that: + - docker_deploy_secrets_checksum is defined + - docker_deploy_configs_checksum is defined + - "'test-app_test_secret' in docker_deploy_secrets_checksum" + - "'test-app_test_config' in docker_deploy_configs_checksum" + fail_msg: "Checksum facts were not properly created" + + - name: Display checksum facts for verification + debug: + msg: + - "Secret checksums: {{ docker_deploy_secrets_checksum }}" + - "Config checksums: {{ docker_deploy_configs_checksum }}" + + - name: Verify secret checksum is a valid SHA hash + assert: + that: + - docker_deploy_secrets_checksum['test-app_test_secret'] | length == 10 + - docker_deploy_configs_checksum['test-app_test_config'] | length == 10 + fail_msg: "Checksums are not the expected length" + + - name: Stop and remove test container + docker_container: + name: test_alpine_secrets + state: absent + ignore_errors: yes + + - name: Clean up test directory + file: + path: "{{ test_base_folder }}" + state: absent