38 Ansible Galaxy und Collections

38.1 Einführung in Ansible Galaxy

38.1.1 Zweck und Funktion

Ansible Galaxy ist die zentrale Plattform für die Verteilung wiederverwendbarer Ansible-Inhalte. Die Plattform ermöglicht es Entwicklern und Administratoren, Code in Form von Rollen und Collections zu teilen, zu suchen und zu installieren. Galaxy fungiert als Repository-Hub für die Ansible-Community und bietet sowohl öffentliche als auch private Inhalte.

38.1.2 Zugriff über CLI und Web

Der Zugriff auf Galaxy erfolgt primär über das ansible-galaxy CLI-Tool, das standardmäßig mit Ansible installiert wird. Die Web-Oberfläche unter https://galaxy.ansible.com dient der Suche und Dokumentation.

# Suche nach Collections
ansible-galaxy collection list
ansible-galaxy search nginx

# Installation einer Collection
ansible-galaxy collection install community.general

38.1.3 Unterschiede zwischen Rollen und Collections

Rollen sind einzelne, funktional abgeschlossene Komponenten mit definierter Verzeichnisstruktur. Collections hingegen sind umfassende Pakete, die mehrere Module, Plugins, Rollen und weitere Ansible-Komponenten enthalten können. Collections bieten eine granularere Namespace-Verwaltung und bessere Versionskontrolle.

38.2 Was sind Ansible Collections?

38.2.1 Struktur und Inhalt einer Collection

Collections folgen einer standardisierten Verzeichnisstruktur:

collection_name/
├── galaxy.yml
├── plugins/
│   ├── modules/
│   ├── inventory/
│   ├── lookup/
│   └── filter/
├── roles/
├── playbooks/
├── docs/
└── tests/

Eine typische galaxy.yml definiert Metadaten:

namespace: example
name: infrastructure
version: 1.0.0
description: Infrastructure management collection
license:
  - GPL-2.0-or-later
authors:
  - IT Operations Team
dependencies:
  community.general: ">=3.0.0"

38.2.2 Vergleich zu klassischen Rollen

Collections kapseln verwandte Funktionalitäten in einem einzigen Paket mit expliziter Namespace-Trennung. Während Rollen primär Tasks und Handlers enthalten, können Collections komplette Module, Plugins und mehrere Rollen bereitstellen:

# Klassische Rolle
- name: Configure nginx
  include_role:
    name: nginx

# Collection-basierte Rolle
- name: Configure nginx
  include_role:
    name: example.infrastructure.nginx

38.2.3 Vorteile für Modularität und Wartbarkeit

Collections ermöglichen semantische Versionierung, Abhängigkeitsmanagement und reduzieren Namespace-Kollisionen. Die Kapselung verwandter Komponenten vereinfacht Updates und Wartung großer Ansible-Codebases.

38.3 Verwendung von Collections

38.3.1 Installation über CLI

Collections werden über ansible-galaxy collection install installiert:

# Installation der neuesten Version
ansible-galaxy collection install community.general

# Installation spezifischer Version
ansible-galaxy collection install community.general:==4.8.0

# Installation aus requirements.yml
ansible-galaxy collection install -r requirements.yml

38.3.2 Angeben von Namespaces und Versionen

Requirements-Dateien definieren Collection-Abhängigkeiten strukturiert:

# requirements.yml
collections:
  - name: community.general
    version: ">=4.0.0,<5.0.0"
  - name: ansible.posix
    version: "1.4.0"
  - name: community.crypto
    source: https://galaxy.ansible.com

38.3.3 Beispiel für die Verwendung von Modulen aus einer Collection

Collections erfordern die vollständige Namespace-Angabe oder Import-Statements:

---
- name: System administration tasks
  hosts: servers
  collections:
    - community.general
  tasks:
    - name: Install package using community.general
      community.general.pacman:
        name: htop
        state: present
      when: ansible_os_family == "Archlinux"

    - name: Alternative ohne collections-Block
      community.crypto.openssh_keypair:
        path: /etc/ssh/ssh_host_rsa_key
        type: rsa
        size: 4096

38.4 Eigene Collections erstellen

38.4.1 Verzeichnisstruktur und Metadaten

Neue Collections werden mit ansible-galaxy collection init erstellt:

ansible-galaxy collection init myorg.infrastructure

Die resultierende Struktur enthält grundlegende Dateien:

# galaxy.yml Beispiel für eigene Collection
namespace: myorg
name: infrastructure
version: 1.0.0
description: Custom infrastructure management
license:
  - Apache-2.0
authors:
  - Internal DevOps Team
repository: https://git.company.com/ansible/infrastructure
documentation: https://docs.company.com/ansible/infrastructure
homepage: https://company.com
issues: https://git.company.com/ansible/infrastructure/issues
build_ignore:
  - "*.tar.gz"
  - ".git"
  - "__pycache__"

38.4.2 Packaging und Veröffentlichung

Collections werden als Tarballs gepackt und können in private oder öffentliche Repositories hochgeladen werden:

# Collection bauen
ansible-galaxy collection build

# Zu privatem Galaxy-Server hochladen
ansible-galaxy collection publish myorg-infrastructure-1.0.0.tar.gz \
  --api-key $GALAXY_API_KEY \
  --server https://galaxy.company.com/

# Lokale Installation für Tests
ansible-galaxy collection install myorg-infrastructure-1.0.0.tar.gz

38.4.3 Beispielhafter Workflow für eigene Collection-Entwicklung

# 1. Collection initialisieren
ansible-galaxy collection init company.monitoring

# 2. Module entwickeln
mkdir -p company/monitoring/plugins/modules
cat > company/monitoring/plugins/modules/check_service.py << 'EOF'
#!/usr/bin/python
from ansible.module_utils.basic import AnsibleModule

def main():
    module = AnsibleModule(
        argument_spec=dict(
            service=dict(type='str', required=True),
            state=dict(type='str', choices=['started', 'stopped'], default='started')
        )
    )
    # Module-Logik hier
    module.exit_json(changed=False, result="Service check completed")

if __name__ == '__main__':
    main()
EOF

# 3. Tests schreiben
mkdir -p company/monitoring/tests/integration/targets/check_service
cat > company/monitoring/tests/integration/targets/check_service/tasks/main.yml << 'EOF'
- name: Test service check module
  company.monitoring.check_service:
    service: sshd
    state: started
  register: result

- name: Verify result
  assert:
    that:
      - result is not changed
EOF

# 4. Collection testen
ansible-test integration check_service

# 5. Collection bauen und verteilen
ansible-galaxy collection build

38.5 Collections in der Praxis

38.5.1 Beispiele für bekannte Collections

community.general: Enthält Module und Plugins, die nicht in ansible-core enthalten sind:

- name: Manage systemd services
  community.general.systemd:
    name: nginx
    state: started
    enabled: yes

- name: Configure logrotate
  community.general.logrotate:
    name: nginx
    path: /var/log/nginx/*.log
    options:
      - daily
      - missingok
      - rotate 52

ansible.posix: POSIX-spezifische Module für Unix-ähnliche Systeme:

- name: Configure authorized keys
  ansible.posix.authorized_key:
    user: deploy
    state: present
    key: "{{ lookup('file', '/path/to/public/key') }}"

- name: Set file ACLs
  ansible.posix.acl:
    path: /srv/data
    entity: webserver
    etype: group
    permissions: rw
    state: present

community.crypto: Kryptographie-bezogene Module:

- name: Generate private key
  community.crypto.openssl_privatekey:
    path: /etc/ssl/private/server.key
    size: 4096

- name: Create CSR
  community.crypto.openssl_csr:
    path: /etc/ssl/csr/server.csr
    privatekey_path: /etc/ssl/private/server.key
    common_name: server.company.com

38.5.2 Best Practices für Versionsmanagement und Updates

Collections sollten semantische Versionierung verwenden und Abhängigkeiten explizit definieren:

# ansible.cfg
[galaxy]
server_list = automation_hub, galaxy

[galaxy_server.automation_hub]
url=https://cloud.redhat.com/api/automation-hub/
auth_url=https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token
token=your_token_here

# requirements.yml mit pinned versions
collections:
  - name: community.general
    version: "==5.5.0"
  - name: ansible.posix
    version: ">=1.4.0,<2.0.0"

Update-Strategien implementieren:

# Prüfung auf verfügbare Updates
ansible-galaxy collection list --format json | jq '.collections'

# Kontrollierte Updates
ansible-galaxy collection install community.general:5.6.0 --upgrade

# Vollständige Neuinstallation
ansible-galaxy collection install -r requirements.yml --force

38.5.3 Integration in bestehende Ansible-Projekte

Collections können schrittweise in bestehende Projekte integriert werden:

# playbook.yml - Migration von legacy modules
---
- name: System configuration
  hosts: all
  collections:
    - community.general
    - ansible.posix
  tasks:
    # Alt: setup module (deprecated)
    # - setup:
    
    # Neu: ansible.builtin.setup (explicit)
    - ansible.builtin.setup:

    # Alt: uri module aus ansible-base
    # - uri:
    
    # Neu: ansible.builtin.uri (explicit namespace)
    - ansible.builtin.uri:
        url: "https://api.service.com/health"
        method: GET
      register: health_check

Projekt-weite Collection-Konfiguration:

# ansible.cfg
[defaults]
collections_paths = ./collections:~/.ansible/collections:/usr/share/ansible/collections

# Automatisches Download bei Playbook-Ausführung
[galaxy]
collection_skeleton_paths = ~/.ansible/collections/ansible_collections