From 93d7cb6bf1c1c65bc25cdb5f5ad506eb269709aa Mon Sep 17 00:00:00 2001 From: "AB from home.homenet" Date: Tue, 16 Sep 2025 15:51:14 +0300 Subject: [PATCH] Added Authentik TF code --- .github/scripts/generate-apps-wiki.py | 143 ++++++++++++++++++++++++++ .github/workflows/update-wiki.yml | 107 +++++++++++++++++++ terraform/authentik/outputs.tf | 29 ++++++ 3 files changed, 279 insertions(+) create mode 100644 .github/scripts/generate-apps-wiki.py create mode 100644 .github/workflows/update-wiki.yml diff --git a/.github/scripts/generate-apps-wiki.py b/.github/scripts/generate-apps-wiki.py new file mode 100644 index 0000000..5e55609 --- /dev/null +++ b/.github/scripts/generate-apps-wiki.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +""" +Script for generating Wiki page with applications list from Terraform outputs +""" + +import json +import sys +import os +from datetime import datetime + +def generate_markdown_table(apps_data): + """Generates Markdown table for applications""" + + # Combine all applications + all_apps = [] + + if 'proxy_apps' in apps_data: + for key, app in apps_data['proxy_apps'].items(): + all_apps.append({ + 'key': key, + 'name': app['name'], + 'type': app['type'], + 'url': app['url'], + 'group': app['group'], + 'description': app['description'], + 'icon': app['icon'], + 'slug': app['slug'] + }) + + if 'oauth_apps' in apps_data: + for key, app in apps_data['oauth_apps'].items(): + all_apps.append({ + 'key': key, + 'name': app['name'], + 'type': app['type'], + 'url': app['url'], + 'group': app['group'], + 'description': app['description'], + 'icon': app['icon'], + 'slug': app['slug'] + }) + + # Sort by groups, then by name + all_apps.sort(key=lambda x: (x['group'], x['name'])) + + # Generate Markdown + markdown = [] + markdown.append("# Authentik Applications") + markdown.append("") + markdown.append(f"*Automatically generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}*") + markdown.append("") + markdown.append("## All Applications") + markdown.append("") + + # Table + markdown.append("| Icon | Name | Type | URL | Group | Description |") + markdown.append("|------|------|------|-----|-------|-------------|") + + for app in all_apps: + icon = f"![]({app['icon']})" if app['icon'] else "📱" + url_link = f"[🔗 Open]({app['url']})" if app['url'] else "-" + description = app['description'] if app['description'] else "-" + + markdown.append(f"| {icon} | **{app['name']}** | {app['type']} | {url_link} | {app['group']} | {description} |") + + markdown.append("") + + # Statistics + proxy_count = len(apps_data.get('proxy_apps', {})) + oauth_count = len(apps_data.get('oauth_apps', {})) + total_count = proxy_count + oauth_count + + markdown.append("## Statistics") + markdown.append("") + markdown.append(f"- **Total applications**: {total_count}") + markdown.append(f"- **Proxy applications**: {proxy_count}") + markdown.append(f"- **OAuth2/OpenID applications**: {oauth_count}") + markdown.append("") + + # Grouping by types + groups = {} + for app in all_apps: + group = app['group'] + if group not in groups: + groups[group] = {'proxy': 0, 'oauth': 0} + if app['type'] == 'Proxy': + groups[group]['proxy'] += 1 + else: + groups[group]['oauth'] += 1 + + markdown.append("## Applications by Groups") + markdown.append("") + for group, counts in sorted(groups.items()): + total = counts['proxy'] + counts['oauth'] + markdown.append(f"- **{group}**: {total} applications (Proxy: {counts['proxy']}, OAuth: {counts['oauth']})") + + markdown.append("") + markdown.append("---") + markdown.append("*This page is automatically generated via Terraform CI/CD*") + + return "\n".join(markdown) + +def main(): + if len(sys.argv) != 2: + print("Usage: python3 generate-apps-wiki.py ") + sys.exit(1) + + output_file = sys.argv[1] + + try: + with open(output_file, 'r') as f: + terraform_output = json.load(f) + + # Извлекаем данные приложений + apps_data = terraform_output.get('applications_for_wiki', {}).get('value', {}) + + if not apps_data: + print("ERROR: No applications_for_wiki output found in Terraform output") + sys.exit(1) + + # Генерируем Markdown + markdown_content = generate_markdown_table(apps_data) + + # Записываем результат + wiki_file = "Applications.md" + with open(wiki_file, 'w', encoding='utf-8') as f: + f.write(markdown_content) + + print(f"✅ Wiki page generated: {wiki_file}") + print(f"📊 Total applications: {len(apps_data.get('proxy_apps', {})) + len(apps_data.get('oauth_apps', {}))}") + + except FileNotFoundError: + print(f"ERROR: File {output_file} not found") + sys.exit(1) + except json.JSONDecodeError as e: + print(f"ERROR: Invalid JSON in {output_file}: {e}") + sys.exit(1) + except Exception as e: + print(f"ERROR: {e}") + sys.exit(1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/.github/workflows/update-wiki.yml b/.github/workflows/update-wiki.yml new file mode 100644 index 0000000..0a576bc --- /dev/null +++ b/.github/workflows/update-wiki.yml @@ -0,0 +1,107 @@ +name: 'Update Authentik Applications Wiki' + +on: + push: + branches: [ "main" ] + paths: + - 'terraform/authentik/**' + workflow_dispatch: + +permissions: + contents: read + +jobs: + update-wiki: + name: 'Generate and Update Wiki' + runs-on: ubuntu-latest + environment: production + + defaults: + run: + shell: bash + working-directory: ./terraform/authentik + + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Setup Terraform + uses: hashicorp/setup-terraform@v2 + with: + cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }} + + - name: Terraform Init + run: terraform init + + - name: Generate Terraform Output + run: | + terraform output -json > terraform-output.json + echo "✅ Terraform output generated" + + - name: Generate Wiki Content + run: | + python3 ../../.github/scripts/generate-apps-wiki.py terraform-output.json + echo "✅ Wiki content generated" + + - name: Upload Wiki to Gitea + run: | + # Set variables + GITEA_URL="${{ secrets.GT_WIKI_URL }}" + GITEA_TOKEN="${{ secrets.GT_WIKI_TOKEN }}" + GITEA_OWNER="${{ secrets.GT_WIKI_OWNER }}" + GITEA_REPO="${{ secrets.GT_WIKI_REPO }}" + + # Check if file was created + if [ ! -f "Applications.md" ]; then + echo "❌ Applications.md not found" + exit 1 + fi + + echo "📤 Uploading to Gitea Wiki..." + + # Encode content to base64 + CONTENT=$(base64 -w 0 Applications.md) + + # Check if wiki page exists + WIKI_PAGE_EXISTS=$(curl -s -o /dev/null -w "%{http_code}" \ + -H "Authorization: token $GITEA_TOKEN" \ + "$GITEA_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/wiki/page/Applications") + + if [ "$WIKI_PAGE_EXISTS" = "200" ]; then + echo "📝 Updating existing wiki page..." + # Update existing page + curl -X PATCH \ + -H "Authorization: token $GITEA_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{ + \"title\": \"Applications\", + \"content_base64\": \"$CONTENT\", + \"message\": \"Update applications list from CI/CD [$(date)]\" + }" \ + "$GITEA_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/wiki/page/Applications" + else + echo "📄 Creating new wiki page..." + # Create new page + curl -X POST \ + -H "Authorization: token $GITEA_TOKEN" \ + -H "Content-Type: application/json" \ + -d "{ + \"title\": \"Applications\", + \"content_base64\": \"$CONTENT\", + \"message\": \"Create applications list from CI/CD [$(date)]\" + }" \ + "$GITEA_URL/api/v1/repos/$GITEA_OWNER/$GITEA_REPO/wiki/new" + fi + + echo "✅ Wiki updated successfully!" + echo "🔗 Wiki URL: $GITEA_URL/$GITEA_OWNER/$GITEA_REPO/wiki/Applications" + + - name: Summary + run: | + echo "## 📊 Wiki Update Summary" >> $GITHUB_STEP_SUMMARY + echo "- ✅ Terraform output extracted" >> $GITHUB_STEP_SUMMARY + echo "- ✅ Applications table generated" >> $GITHUB_STEP_SUMMARY + echo "- ✅ Wiki page updated in Gitea" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "**Applications count:** $(grep -c '|.*|.*|.*|.*|.*|' Applications.md || echo 0)" >> $GITHUB_STEP_SUMMARY + echo "**Generated at:** $(date)" >> $GITHUB_STEP_SUMMARY \ No newline at end of file diff --git a/terraform/authentik/outputs.tf b/terraform/authentik/outputs.tf index f55c287..cfe7897 100644 --- a/terraform/authentik/outputs.tf +++ b/terraform/authentik/outputs.tf @@ -91,4 +91,33 @@ output "certificates" { fingerprint_sha1 = v.fingerprint_sha1 } } +} + +# Output for applications table generation +output "applications_for_wiki" { + description = "Applications data formatted for wiki table generation" + value = { + proxy_apps = { + for k, v in var.proxy_applications : k => { + name = v.name + type = "Proxy" + url = v.external_host + group = v.group + description = v.meta_description + icon = v.meta_icon + slug = v.slug + } + } + oauth_apps = { + for k, v in var.oauth_applications : k => { + name = v.name + type = "OAuth2/OpenID" + url = length(v.redirect_uris) > 0 ? "https://${split("/", replace(v.redirect_uris[0], "https://", ""))[0]}" : "" + group = v.group + description = v.meta_description + icon = v.meta_icon + slug = v.slug + } + } + } } \ No newline at end of file