Files
vpn-node-config/.ansible/collections/ansible_collections/community/general/AGENTS.md
T
gitea_admin 72fb458dab
OpenVPN Ansible / Deploy VPN Networking and OpenVPN (push) Canceled after 0s
OpenVPN Ansible / Generate SBOM (push) Canceled after 0s
OpenVPN Ansible / Scan SBOM with Trivy (push) Canceled after 0s
OpenVPN Ansible / Ansible Syntax Check (push) Canceled after 38s
OpenVPN Ansible / Ansible Lint (push) Canceled after 40s
fix(vpn-node-config): resolve ansible-lint violations
2026-11-11 12:13:20 +01:00

30 KiB

Rules for community.general

Scope Discipline

  • Stay strictly within the scope of the current task or branch. Do not add extra changes, improvements, or cleanups unless explicitly requested.
  • Do not introduce deprecations as a side effect of other changes. Only add a deprecation when the branch/PR is specifically about that deprecation.
  • When in doubt about whether a change is in scope, ask before making it.

Ansible Collection

  • This collection follows Semantic Versioning.
  • Being an Ansible collection, its version number is specified in the galaxy.yml.
  • The version set there, for the main branch is the next version to be released that accepts new features.
  • For this collection, you will want to read the description of the issue: https://github.com/ansible-collections/community.general/issues/11482
  • The guidelines for contributors are found in the CONTRIBUTING.md.
  • It is very important to maintain backwards compatibility in the changes.
  • When something needs to change and break that, a longer process must be taken, involving deprecations and sometimes feature flags to enable the new behavior.
  • Deprecations usually plan for the removal of the deprecated code in two major versions (X+2).0.0 from the current version. Depending on the situation, this target may be pushed for the (X+3).0.0 version.
  • If a deprecation is needed, ingest https://github.com/russoz-ansible/ansible-contrib-unofficial/blob/main/deprecations.md for more information on how to implement the deprecations.
  • Always refer to modules and plugins by their FQCN.
  • Use version_added to record in which version something new became available:
    • Always read galaxy.yml from current main and use that version string directly — it holds the next version for a feature release.
    • New module or plugin: set version_added at the top level of DOCUMENTATION.
    • New option or suboption in an existing module or plugin: set version_added in that option's documentation. Options that come together with a new module or plugin do not need it.
    • New option or suboption in a doc fragment: do not set version_added in the doc fragment itself. Instead, in each module or plugin using the fragment that existed before that version, add only version_added for that option under options (see the token option in consul_session.py). Keys set there replace the same keys from the fragment, all other keys are kept.
    • New choice value or new alias for an existing option: there is no version_added field for these, so add a paragraph to the option's description instead, for example:
      - The value V(all) has been added in community.general 13.5.0.
      - The O(client_id) alias has been added in community.general 13.5.0.
      
    • Do not add or change version_added for things that already existed.
    • Once that version is released, the value is stale. After rebasing, or when a release happened while the PR was open, read galaxy.yml from the updated main again and update every version_added (and description note) added by the PR.

This project abides to the REUSE specification from the Free Software Foundation. They provide a tool, reuse, to check for compliance; the command nox -e license-check can be used to perform that check, but only when a marker is added, changed or removed.

  • All new content added to this collection must fall under the GPL-3 license.
  • Every file should have a license and copyright markers.
  • These markers should be placed as comments by the beginning of the file. If the file has a "shebang", then it should start in line 2, otherwise, in line 1. Alternatively, the license should be placed in another file with the exact same name, plus a suffix .license, when:
    • The file format does not allow comments.
    • The file is automatically generated by some process.
  • The directory changelog/fragments is exempt from this rule, as defined in REUSE.toml.
  • The format of the marker will typically consist of 3 or more lines. Example:
    # Copyright (c) 2018, Ansible Project
    # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
    # SPDX-License-Identifier: GPL-3.0-or-later
    
    There might be multiple Copyright lines, for different authors.
  • Whenever you create a new copyright marker, check the current date and use the current year.
  • Do not update dates in existing copyright markers.

Deprecation Rules

Reference guide: https://github.com/russoz-ansible/ansible-contrib-unofficial/blob/main/deprecations.md

Deprecating a parameter with no default value

Use removed_in_version + removed_from_collection in argument_spec, plus a description note in the docs.

Deprecating a parameter that has a default value

Do NOT use removed_in_version — it triggers on every run because the parameter is always resolved (via its default), even when the user never explicitly set it.

Instead:

  • Remove default from argument_spec
  • Remove default: from the docs; describe the old default in the description text alongside the deprecation note
  • In main(), detect None (meaning the user didn't set it), apply the old default manually, and call:
    module.deprecate(
        "The <param> option will be removed ...",
        version="X.Y.0",
        collection_name="community.general",
    )
    
    Depending on the option, only call module.deprecate() if the changing default has an effect on the task.

Removal target versions

  • Default: plan removal at (X+2).0.0 from the current major version
  • May be pushed to (X+3).0.0 depending on the situation

Writing plugin code

  • Modules and module utils run on the target nodes, other plugins run on the controller. Check https://github.com/ansible-collections/community.general/issues/11482 for the lowest Python version supported on each side, and do not use language or standard library features newer than that (e.g. str.removesuffix() requires Python 3.9).
  • Access module parameters with module.params["name"], not module.params.get("name"): every option declared in the argument spec is always present, set to None when it has no value and no default.
    • module.params.get("name", <fallback>) is misleading, since the fallback is never used. Declare a default in the argument spec instead.
    • The same applies to the suboptions of a dict option, when that option is set.
    • When working on a module that still uses .get(), use [] in the code being added or changed.
    • Unit tests that mock module.params must provide all options of the argument spec.
  • Type hints:
    • Use import typing as t, not from typing import ....
    • Use X | None instead of t.Optional[X].
    • Do not use t.Any for objects from third-party libraries, it disables type checking for them.
    • In filter and test plugins, the input can be anything the user passes: type it as t.Any and validate it.
    • In modules, type the argument spec and the return values with the helper types from plugins/module_utils/_typing.py:
      • Import them, and define the types built from them, inside an if t.TYPE_CHECKING: # pragma: no cover block. They are only used in annotations, which are not evaluated at runtime (from __future__ import annotations).
      • Build the argument spec in a function get_argument_spec() -> ArgumentSpecT, and pass its result to AnsibleModule().
      • Type the result dictionary as a TypedDict that combines the ModuleReturn* types for the standard return values (changed, msg, rc, stdout, stderr, backup_file, diff) with the module-specific ones. The *Req variants make the key required.
      if t.TYPE_CHECKING:  # pragma: no cover
          from ansible_collections.community.general.plugins.module_utils._typing import (
              ArgumentSpecT,
              ModuleReturnBackupFile,
              ModuleReturnChangedReq,
              ModuleReturnDiff,
          )
      
          class ResultDict(ModuleReturnChangedReq, ModuleReturnBackupFile, ModuleReturnDiff[str]):
              config_file: str
              config_content: str | None
              enabled_state: bool
      
      
      def get_argument_spec() -> ArgumentSpecT:
          return dict(
              name=dict(type="str", required=True, aliases=["config_name"]),
              state=dict(type="str", choices=["present", "absent"], default="present"),
              config_dir=dict(type="path", default="/etc/logrotate.d"),
              paths=dict(type="list", elements="path"),
          )
      
  • When handling user-provided data structures, use collections.abc.Mapping, collections.abc.Sequence, and ansible.module_utils.common.collections.is_sequence instead of checking for dict and list.
  • Compile regular expressions once, outside of loops, and use the compiled object inside the loop.
  • Do not place code or constants (other than conditional imports) before the imports. Imports come after the DOCUMENTATION, EXAMPLES, and RETURN strings.
  • Do not use names starting with _ for variables or methods in module files.
  • Avoid redundant code, for example:
    • Conversions to a type the value already has (str() on a string, bool() on a boolean, str(e) inside an f-string).
    • if changed == True: instead of if changed:.
    • x if x is not None else "" where x or "" does the same.
    • Comments that only restate the code.
  • Extract code that is repeated (e.g. building the same URL in several places) into a function.

Writing plugin documentation

  • Use semantic markup: O() for options, V() for values, RV() for return values, C() for code, commands, and paths. See https://docs.ansible.com/projects/ansible/latest/dev_guide/ansible_markup.html.
  • Each description is a list of paragraphs:
    • Do not split a sentence over two list items.
    • Keep information about the same subject in the same paragraph.
  • Do not list the possible values in the description when the option has choices, they are rendered automatically.
  • When documenting what each choice does, prefer making choices a dictionary that maps each value to its description, instead of explaining the values in the option's description. Each value's description can be a string or a list of paragraphs. Use:
    description:
      - The mode of the node.
    choices:
      normal: Utilizes this node as much as possible.
      exclusive:
        - Only builds jobs with label expressions matching this node.
        - Additional paragraph.
    
    instead of:
    description:
      - The mode of the node.
      - If V(normal), utilizes this node as much as possible.
      - If V(exclusive), only builds jobs with label expressions matching this node.
    choices: [normal, exclusive]
    
  • Values of state describe the resulting state (present, absent, built, initialized), not the command run to reach it (build, init).
  • Describe boolean options by what happens when they are V(true).
  • Do not add aliases to options unless strictly necessary.
  • In new features, use the current terminology of the tool or service being managed, not legacy names.
  • State explicitly any behavior that is not obvious for users who are not Python programmers, for example:
    • Comparing values with equality treats 0 and false (and 1 and true) as equal.
    • re.match() only matches at the beginning of the string.
    • A list value must be passed nested inside another list when the option takes a list of values.
  • Attributes:
    • Add community.general._attributes to extends_documentation_fragment.
    • Under each attribute set support and, when needed, details. Do not set description, it comes from the doc fragment.
    • Use details to explain limitations; it is usually not needed for support: full.
  • Keep lines in EXAMPLES short: move long values into vars: or use YAML folded scalars.
  • Separate the DOCUMENTATION, EXAMPLES, and RETURN strings with a blank line.

Check mode, diff mode, and idempotency

  • In check mode the module must not change anything, but it must report the same changed value a real run would. Do not return a fixed changed value in check mode.
  • Determine changed by comparing the requested state with the current state of the system or service. Do not report changed=true just because an action was performed: many APIs and commands are idempotent and do not tell whether anything changed.
  • An attribute (check_mode, diff_mode) may only declare support: full if every code path honors it. Otherwise declare support: partial and explain the limitation in details. New states and options added to a module that declares full support must honor it as well.
  • Normalize values before comparing them, so that equivalent values do not produce a change on every run (e.g. None versus "", human-readable sizes versus bytes).
  • In diff mode, return diff with before and after. When the content of a file is compared, also set before_header and after_header to the paths, the same way ansible.builtin.copy does.

Validating input and designing behavior

  • Express constraints between options in the argument spec (required_if, required_together, required_one_of, required_by, mutually_exclusive). Only check in code what the argument spec cannot express.
  • Reject contradictory or meaningless combinations of options. Do not silently pick one of them or ignore the other.
  • Never silently transform, discard, or ignore user input:
    • If the input cannot be applied as given, fail with a clear message.
    • If a lenient behavior is useful, make it configurable (e.g. fail, warn, ignore) with failing as the default.
    • If an operation requires an existing object (e.g. archiving a project), fail when it does not exist.
  • When the module has to make an assumption (e.g. the server version cannot be determined), emit a warning with module.warn().
  • When wrapping a CLI tool or an API, pass on its warnings and errors instead of re-implementing its checks.
  • Prefer backward compatible, additive changes, such as a new choice value or a new alias, over changing defaults or deprecating options.
  • Prefer choices with descriptive strings over booleans when the meaning of true/false is not obvious.
  • Keep messages neutral and accurate, e.g. "Project not found" instead of "Project deleted or does not exist".
  • Do not add options or safeguards that nobody asked for. They can be added later when there is an actual need.

Writing changelog fragments

Changelog Fragments:

  • MUST be created for modifications in the productive code (mostly code under plugins/)
  • MUST NOT be created for:
    • New modules or new plugins, including changes to module utils or plugin utils that only affect the new module or plugin. Changes to those utils that affect previously existing modules or plugins MUST be recorded.
    • Changes touching only documentation, comments, and/or tests.
  • MUST be files in changelogs/fragments named as <PR number>-<some description, possibly matching the branch name>.yml.
  • MUST have a dict as the top-level element, and the keys MUST be one of: minor_changes, breaking_changes, deprecated_features, removed_features, bugfixes.
  • MUST list, under each top-level element, one entry for each plugin changed or affected by the PR.
  • MUST use the format:
      - <component spec> - <description> (<URLs>).
    
    for the entries.
    • The "component spec" is different for different types of plugins, in this order:
      • Modules (plugins/modules): "" (or )
      • Module utils (plugins/module_utils): " module utils"
      • Plugin utils (plugins/plugin_utils): " plugin utils"
      • All other plugins (plugins/<PLUGIN_TYPE>/): " <PLUGIN_TYPE> plugin"
      • Groups of related modules or plugins may share one entry using a wildcard, with exclusions if needed (e.g. "ldap_* modules", "foo_* modules except foo_bar").
      • Plugin filenames starting with _ are generally not to be added to the changelog fragment. When a change in such a file affects previously existing modules or plugins:
        • If the change is relevant to users of those modules or plugins (e.g. it fixes a bug or changes their behavior), add entries for the affected modules or plugins, using wildcards where possible.
        • If the change is not visible to users (e.g. a refactoring), add a single entry for the utils file instead (e.g. "_cmd_runner module utils").
    • The description MUST be a single short sentence stating what changed, from the user's perspective. Do NOT explain why the change was made, how it was implemented, or what Python constructs were used. Do not provide examples of values. The audience is end users and operators, not developers; avoid implementation details. No need to provide details that can be found in the issue or in the PR. That content should be in RST format, so for example symbol names must be enclosed in double back ticks, as in "symbol". Use American English spelling (e.g. "behavior" not "behaviour", "customize" not "customise"). Description must start with lower-case - do not capitalize the first word. Acronyms are always written in upper-case, anywhere in the description, including as the first word (e.g. "API", "URL"). If the description contains : , quote the entire entry to prevent YAML errors.
    • The URLs - every entry MUST include the full URL of the PR itself, no exceptions. An entry without the PR URL is invalid, even if it links one or more issues. If the PR fixes one or more issues, the URLs of those issues MUST be included as well, preferably before the PR URL. The URLs must be separated with , . For example:
      bugfixes:
        - xfconf - fix idempotency for list values (https://github.com/ansible-collections/community.general/issues/1234, https://github.com/ansible-collections/community.general/pull/5678).
      
  • SHOULD NOT mix bugfixes with other changes: fixes are backported and no new features should come along
  • SHOULD NOT mix deprecated_features with other changes

Given the fact that the PR number is required for the file name and for the URLs part of the entry, the fragment must be generated (then committed and pushed) after the PR is first created. Do not write the fragment before the PR exists, and never leave out the PR URL or use a placeholder for it.

After drafting a changelog fragment, always present it to the user for review and explicit approval before committing or pushing it.

BOTMETA Rules

  • Add an entry to the .github/BOTMETA.yml file every time a new file is added within the paths:
    • docs/docsite/rst/**
    • plugins/**
  • The entry should be placed within the existing section where it belongs, and within that section, files should be listed on alphabetical order.
  • User handles are never removed, unless explicitly requested.

Git usage

  • Never mention any user or group with @ in the commit message.
  • Before committing changes:
    • Ensure you are in the right branch
    • If containing code changes, look for unit and integration tests and apply them as possible
  • When branching:
    • Always ensure you are branching off the main branch
    • Do not use fix or any other prefix indicating the type of the branch
    • If there is an issue associated with the branch, prefix the name with ####- (where #### is the issue number), e.g. if fixing issue 9999 about the xfconf module, name it like 9999-xfconf-something.

Github Issues Rules

  • Classify issues correctly: features are not bugfixes even if they address a gap or missing behavior. Use the issues template's categories accurately.

    • For an issue to be considered a bug, it must refer to a behavior promised in the plugin documentation or something that defeats its purpose. Elective preferences are not bugs. Missing features are not bugs.
  • The "Community.general Version" and "Ansible Version" fields must report the versions used to detect the problem and they should be supported versions of: the collection itself, ansible-core, Python.

  • MUST use one of the templates in .github/ISSUE_TEMPLATE

    • Component name: one per line, use the relative path in the repo, one per line
    • Community.general version: if bug exists in main branch, simply state so.
    • Do generate the Code of Conduct checkbox - I am responsible for what you do, my child
  • When the issue is about code:

    The issue title must follow:

    Case Format Example
    Module issue <name>: <summary> postgresql_db: fails when password contains special characters
    Non-module plugin <name> <type> plugin: <summary> passwordstore lookup plugin: add support for multiline secrets
    New plugin request <name>: new module or <name>: new <type> plugin proxmox_vm: new module
    Multiple related plugins <common_prefix>*: <summary> proxmox*: multiple modules fail with newer API versions
    Multiple unrelated plugins multiple: <summary> multiple: deprecation warnings not shown correctly
    • Use lowercase for the summary part (after the colon).
    • Strip noise words: "Issue with", "Bug:", "[BUG]", "[FR]", "Request:".
    • When in doubt about the plugin name, skim the issue body for FQCN references or task examples.
  • When the issue is NOT about code:

    An issue title like below is suggested (never enforced) to the user:

    Case Format Example
    Non-plugin (CI, docs, infra) docs:, CI:, testing:, build:, meta: prefix docs: update contribution guidelines

Github Pull Request Rules

  • MUST use the template .github/pull_request_template.md
  • MUST create the PR in the upstream repository
  • Classify PRs correctly: features are not bugfixes even if they address a gap or missing behavior. Use the PR template's categories accurately.
  • Do not comment in the description about the state of the changelog fragment.
  • The PR title should be in one of the forms:
    • <module>: <short-description> e.g. xfconf: adjust return value
    • <plugin> <plugin-type> plugin: <short-description> e.g. pbrun become plugin: refactor function xyz()
    • new module/<plugin-type> plugin: <name> <short-description> e.g. new module: xyz interacts with XyZ service or new inventory plugin: abc retrieves hosts from ABC daemon
  • PR title should use short names for modules/plugins, e.g. xfconf instead of community.general.xfconf
  • PR title should use single backticks for terms like commands, variables, functions, etc. E.g. "xfconf: use command xfconf-query"
  • PR title may have a prefix indicating it is a work in progress. E.g. "[WIP] xfconf: use command xfconf-query"
  • If the PR fixes issues, add one line with Fixes #<issue-number> for each issue being solved to the PR description
  • Do not create an issue for the PR after creating the PR.
  • Do not place GitHub closing keywords (close, fix, resolve and their variants) right before an issue reference unless the PR fixes that issue: GitHub links the issue even if the sentence negates it (e.g. "does not close #1234"). Write "issue #1234" instead.
  • Bugfixes and security fixes may be backported to older stable branches; new features are not. The classification of the PR determines that.
  • When the PR is ready for review, mark it as ready (not draft) and remove any [WIP] prefix from the title.
  • When a fix is speculative or lacks test coverage, use hedged language in the PR description (e.g. "may address" rather than "this fixes").
  • Keep PR descriptions concise; do not explain implementation choices or reproduce information already visible in the diff or commit messages.
    • Do NOT list the tests run locally (sanity, unit, integration, or manual runs) nor their results. They are only relevant to the author; CI runs the tests for the PR. Exception: when integration tests affected by the PR do not run in CI (e.g. the target is marked as disabled or unsupported), briefly state which of them were run locally and on which platforms.
    • Code in the PR description MUST be limited to one small snippet demonstrating the change, e.g. a single task. Do NOT include full playbooks, long task lists, or long code blocks in any language. If a longer reproducer or example is useful, post it later in a separate PR comment.
    • Fence all code blocks with the proper language tag: yaml for Ansible code, python for Python code, and so on.

Tests

Running Tests

  • Run sanity tests with: ansible-test sanity --docker default --python 3.14 <files> (omit files to test everything)
  • Run unit tests with: ansible-test units --docker default --python 3.14 tests/unit/plugins/<plugin_type>/<test_file.py> (omit the path to test everything)
  • Run integration tests with: ansible-test integration --docker default --python 3.14 <target name> (omit target to test everything, but that is discouraged as it takes a long while)
    • Some integration tests require a proper OS container (ubuntu, fedora, alpine) instead of the default container (default). For OS containers, do not specify --python <version>.
    • Some integration tests must run on a full VM, not in a container (e.g. snap)
  • PRs are only merged into main if they pass the tests
  • Do not re-run a test suite that already passed in the current session unless new code changes have been made since the last run.

Writing unit tests

  • Prefer pytest idioms to write tests
    • Prefer plain functions instead of Test classes
    • Use pytest fixtures when applicable
    • Avoid unittest class-based tests
  • Use mocker to mock patch symbols
  • Use the common tools from community.internal_test_tools when applicable, instead of reinventing the wheel.
    • E.g. ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils.set_module_args
  • When testing modules that call CLI commands, prefer uthelper. Other tests can be mixed with the UTHelper call.
  • Try and avoid adding new entries to the tests/unit/requirements.txt file, as it is installed every time, for every unit testing, no matter how small or unrelated to the requirements it might be.
  • Tests should:
    • Mock all interaction with external services, APIs, commands
    • NEVER mock the entire module - it defeats the purpose of the testing. Instead, run the module and capture the SystemExit exception from it.
    • Assert the "happy-path" for the module execution. There might be multiple ones (changes, no changes, partial changes).
    • Assert some exception paths (when things go wrong) are handled as gracefully as possible
    • NOT assert Ansible features, e.g. if two parameters are marked in the argument spec as mutually exclusive, there is no need to write a test to verify that they cannot be used together. It is a given, and ansible-core has plenty of tests for those.
    • NOT assert static data, such as the contents of the argument spec.
    • Assert negative outcomes where relevant, i.e. that something was not done (e.g. no command executed in check mode, only the expected values registered as secrets).
  • Do not add if __name__ == "__main__": blocks to unit test scripts.
  • Do not patch sys.modules to inject mocks. Import the module normally and patch symbols with mocker.

Writing integration tests

  • The generic documentation on integration tests is found at: https://docs.ansible.com/projects/ansible/latest/dev_guide/testing_integration.html
  • Each directory under tests/integration/targets is akin to an Ansible role
  • The aliases files contains directives that control how/where the tests are executed.
  • Targets named setup_* are actual supporting roles. Some noteworthy ones:
    • setup_remote_tmp_dir
    • setup_snap
    • setup_docker
    • setup_pkg_mgr
  • Tests should:
    • Interact with the actual external services, APIs, commands
      • This may not be feasible for some third party services requiring authentication, paid services, etc
    • Use local alternatives as possible, e.g. docker images (use setup_docker)
    • Be implemented in a "black-box" style: we provide inputs and assert the outputs, not interested in the internal details
    • Assert idempotency, i.e. run the same command twice and assert the second time bears no change
      • One repeated run is enough to verify idempotency
      • Also test changing an attribute of an object that already exists in the requested state
    • Assert only the values the test changed, not entire configurations or outputs
    • Test error paths with a regular task using ignore_errors: true and register, then assert that the result is failed and that its msg contains the expected error. Do not write and execute separate playbooks for that.
    • Use FQCNs everywhere, including lookups and filters (e.g. lookup('ansible.builtin.template', ...))
    • Use distinct, descriptive names for registered variables
    • Not depend on variables that can only be set on the command line - CI cannot set them
    • Keep resource usage (disk images, downloads) as small as possible, CI VMs have limited resources
  • For targets that only work on some platforms:
    • Add skip/<platform> entries (e.g. skip/macos, skip/freebsd, skip/alpine) to aliases
    • Also skip unsupported systems at the start of the tasks, before installing packages or doing any other setup work, since the aliases do not cover every environment CI uses (e.g. skip/alpine does not skip the Alpine container)
    • Do not add precondition assertions or messages explaining why something is skipped, they only add noise
  • For modules with larget sets of functions, break the tests into smaller files and use include_tasks

Use of AI for contributions

Please note that using AI is accepted but you MUST comply with the Ansible Community Policy for AI-Assisted Contributions!

The main points are:

  • Be transparent: disclose the use of AI when a significant part of the contribution is taken from the AI output without significant changes. Grammar, spelling, and style corrections do not need disclosure.
    • In commits, add a trailer Assisted-by: <model>, e.g. Assisted-by: Claude Opus 5.5.
    • In issues, PR descriptions, and comments, add a short note stating that AI was used.
  • Contributions assisted by AI must follow the project's standards and guidelines, including this file.
  • The contributor is fully accountable for the contribution, with or without AI assistance.