Skip to content

Commit

Permalink
Merge pull request #2 from GlueOps/feat/init
Browse files Browse the repository at this point in the history
feat: initial commit
  • Loading branch information
NichArchA82 authored Oct 19, 2024
2 parents cb0a077 + c29944e commit b0ca718
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 0 deletions.
56 changes: 56 additions & 0 deletions .github/workflows/container_image.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
name: Publish to GHCR.io

on: [push]

env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}

jobs:
build_tag_push_to_ghcr:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write

steps:
- name: Checkout repository
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4


- name: Set up QEMU
uses: docker/setup-qemu-action@68827325e0b33c7199eb31dd4e31fbe9023e06e3 # v3

- name: Setup Docker buildx
uses: docker/setup-buildx-action@d70bba72b1f3fd22344832f00baa16ece964efeb # v3.3.0

- name: Log into registry ${{ env.REGISTRY }}
uses: docker/login-action@0d4c9c5ea7693da7b068278f7b52bda2a190a446 # v3.2.0
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@8e5442c4ef9f78752691e2d8f8d19755c6f78e81 # v5.5.1
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch,prefix=
type=ref,event=tag,prefix=
type=sha,format=short,prefix=
type=sha,format=long,prefix=
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5.4.0
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
provenance: false
cache-from: type=gha
cache-to: type=gha,mode=max
15 changes: 15 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Use an official Python runtime as a parent image
FROM python:3.11.9-alpine@sha256:1bcefb95bd059ea0240d2fe86a994cf13ab7465d00836871cf1649bb2e98fb9f

WORKDIR /app
# Copy the files into the Docker image
COPY main.py requirements.txt /app/

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Make port 8000 available to the world outside this container
EXPOSE 8000

# run the app
CMD ["fastapi", "run", "main.py", "--host", "0.0.0.0", "--port", "8000"]
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,17 @@
# gatekeeper

send webhooks to this app to run github user management

## Developer setup

- create a github organization for testing
- create a PAT(classic) that has full access
- create a workflow to call (or use github user management workflow)
- etup webhooks at organization level for repository events

### required env variables

```bash
GITHUB_DISPATCH_URL=https://api.github.com/repos/<GITHUB_ORG_NAME>/<GITHUB_REPO_NAME>/actions/workflows/sync.yaml/dispatches
GITHUB_TOKEN=<PAT_TOKEN>
```
76 changes: 76 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from fastapi import FastAPI, Request, HTTPException
from contextlib import asynccontextmanager
import os
import requests

#ENV variables
GITHUB_DISPATCH_URL = os.getenv('GITHUB_DISPATCH_URL')
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')

@asynccontextmanager
async def lifespan(app: FastAPI):
"""Startup function to test env variables
crashes if env variables are not set
Args:
app (FastAPI)
Raises:
Exception: env variables not set
"""

required_env_vars = ["GITHUB_DISPATCH_URL", "GITHUB_TOKEN"]

for var in required_env_vars:
if var not in os.environ:
raise Exception(f"Environment variable {var} is not set.")
yield

#define the FastAPI app with lifespan
#for startup function
app = FastAPI(lifespan=lifespan)

@app.post("/v1/")
async def trigger_workflow(request: Request):
"""Triggers the workflow if repository created
Other events are ignored
Args:
request (Request): Incoming webhook from GitHub
Raises:
HTTPException: Sends 500 status code if
there is an issue in triggering workflow
Returns:
string: status message for user
"""
if "x-github-event" in request.headers:
if request.headers["x-github-event"] == "repository":
#get the request body in json
reqBody = await request.json()
if 'action' in reqBody:
if reqBody["action"] == "created":
try:
status_code = call_github_user_management_workflow()
if status_code == 204:
return("workflow triggered")
raise Exception()
except:
raise HTTPException(status_code=500, detail="issues triggering workflow")

return "no workflow triggered"

def call_github_user_management_workflow():
"""Calls the github user management workflow
Returns:
int: status code
"""
# Set the Content-Type header to application/json
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {GITHUB_TOKEN}", "X-GitHub-Api-Version": "2022-11-28"}

# Send POST request with JSON data
response = requests.post(url=GITHUB_DISPATCH_URL, data='{"ref":"refs/heads/main"}', headers=headers)

# return the status code
return response.status_code
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fastapi[standard]==0.115.2
requests==2.32.3

0 comments on commit b0ca718

Please sign in to comment.