Skip to content

Conversation

phavekes
Copy link
Member

No description provided.

Copy link
Member

@pmeulen pmeulen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

'inventory_dir': inventory_dir | default(None),
'playbook_dir': playbook_dir | default(None),
'ansible_cmdline': lookup('file', '/proc/self/cmdline') | regex_replace('\u0000',' ') | default(None),
'ansible_forks': ansible_forks | default(None),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to add the local git version of openconext-deploy, environments-external and roles-external?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i.e., include the results of:

git describe --all --tags; 
test -d roles-external && cd roles-external git describe --all --tags || echo "not found"; 
test -d environments-external && cd environment-external && git describe --all --tags || echo "not found"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Junie AI suggests this approach:

# -*- coding: utf-8 -*-
"""
Ansible lookup plugin: git_revision

Returns the git revision description of the current working repository, similar to
`git describe --all --tags`.

Usage in playbooks/templates:
  - debug: msg="{{ lookup('git_revision') }}"
  # Or in Jinja2 templates
  {{ lookup('git_revision') }}

If the command fails (not a git repo or git not installed), it returns an empty string
and logs a warning on the controller.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type

import subprocess
from typing import List, Optional

from ansible.plugins.lookup import LookupBase
from ansible.utils.display import Display


display = Display()


class LookupModule(LookupBase):
    """Lookup plugin that returns `git describe --all --tags` for the current repo."""

    def run(self, terms: List[str], variables: Optional[dict] = None, **kwargs) -> List[str]:
        # Allow optional 'path' kwarg to run the command in a specific directory.
        path = kwargs.get('path') or kwargs.get('cwd')

        cmd = [
            'git',
            'describe',
            '--all',
            '--tags',
        ]

        try:
            result = subprocess.check_output(
                cmd,
                stderr=subprocess.STDOUT,
                cwd=path if path else None,
            ).decode('utf-8').strip()
        except Exception as e:
            # Don't fail a play because of this; log warning and return empty string
            message = getattr(e, 'output', None)
            if isinstance(message, (bytes, bytearray)):
                try:
                    message = message.decode('utf-8', errors='ignore')
                except Exception:  # pragma: no cover - best effort decoding
                    message = str(e)
            if not message:
                message = str(e)
            display.warning("git_revision lookup failed; returning empty string. Details: %s" % message)
            result = ''

        # Lookup plugins must return a list. We return single-element list.
        return [result]

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or even nicer:

# -*- coding: utf-8 -*-
"""
Ansible lookup plugin: git_revision

Returns the git revision description of the current working repository, similar to
`git describe --all --tags`.

Usage in playbooks/templates:
  - debug: msg="{{ lookup('git_revision') }}"
  # Or in Jinja2 templates
  {{ lookup('git_revision') }}

This version uses native Python Git modules instead of running a shell command.
If GitPython is unavailable or the directory is not a Git repository, it returns
an empty string and logs a warning on the controller.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type

import os
from typing import List, Optional

from ansible.plugins.lookup import LookupBase
from ansible.utils.display import Display


display = Display()

try:
    # GitPython
    from git import Repo  # type: ignore
except Exception:  # pragma: no cover - optional dependency
    Repo = None  # type: ignore


class LookupModule(LookupBase):
    """Lookup plugin that returns a Git describe-like string for the current repo."""

    def run(self, terms: List[str], variables: Optional[dict] = None, **kwargs) -> List[str]:
        # Allow optional 'path' kwarg to point to a specific directory.
        path = kwargs.get('path') or kwargs.get('cwd')
        cwd = path or os.getcwd()

        result = ''

        if Repo is None:
            display.warning("git_revision lookup: GitPython not installed; returning empty string.")
            return [result]

        try:
            repo = Repo(cwd, search_parent_directories=True)
            # Use GitPython's git wrapper to call 'describe'. While GitPython may
            # use the git binary under the hood, from Ansible we are no longer
            # spawning a subprocess directly.
            desc = repo.git.describe('--all', '--tags')
            result = desc.strip()
        except Exception as e:
            display.warning("git_revision lookup failed; returning empty string. Details: %s" % (str(e),))
            result = ''

        # Lookup plugins must return a list. We return single-element list.
        return [result]

'inventory_dir': inventory_dir | default(None),
'playbook_dir': playbook_dir | default(None),
'ansible_cmdline': lookup('file', '/proc/self/cmdline') | regex_replace('\u0000',' ') | default(None),
'ansible_forks': ansible_forks | default(None),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or even nicer:

# -*- coding: utf-8 -*-
"""
Ansible lookup plugin: git_revision

Returns the git revision description of the current working repository, similar to
`git describe --all --tags`.

Usage in playbooks/templates:
  - debug: msg="{{ lookup('git_revision') }}"
  # Or in Jinja2 templates
  {{ lookup('git_revision') }}

This version uses native Python Git modules instead of running a shell command.
If GitPython is unavailable or the directory is not a Git repository, it returns
an empty string and logs a warning on the controller.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type

import os
from typing import List, Optional

from ansible.plugins.lookup import LookupBase
from ansible.utils.display import Display


display = Display()

try:
    # GitPython
    from git import Repo  # type: ignore
except Exception:  # pragma: no cover - optional dependency
    Repo = None  # type: ignore


class LookupModule(LookupBase):
    """Lookup plugin that returns a Git describe-like string for the current repo."""

    def run(self, terms: List[str], variables: Optional[dict] = None, **kwargs) -> List[str]:
        # Allow optional 'path' kwarg to point to a specific directory.
        path = kwargs.get('path') or kwargs.get('cwd')
        cwd = path or os.getcwd()

        result = ''

        if Repo is None:
            display.warning("git_revision lookup: GitPython not installed; returning empty string.")
            return [result]

        try:
            repo = Repo(cwd, search_parent_directories=True)
            # Use GitPython's git wrapper to call 'describe'. While GitPython may
            # use the git binary under the hood, from Ansible we are no longer
            # spawning a subprocess directly.
            desc = repo.git.describe('--all', '--tags')
            result = desc.strip()
        except Exception as e:
            display.warning("git_revision lookup failed; returning empty string. Details: %s" % (str(e),))
            result = ''

        # Lookup plugins must return a list. We return single-element list.
        return [result]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants