Repository: HexCoderTech/github-actions-demo Branch: main Commit: 65f6ed867c5d Files: 17 Total size: 17.5 KB Directory structure: gitextract_v1nocjzt/ ├── .github/ │ └── workflows/ │ ├── deploy.yml │ ├── pull-request.yml │ └── release.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── requirements-dev.txt ├── src/ │ └── api/ │ ├── main.py │ ├── requirements.txt │ └── weather.py ├── terraform/ │ ├── .terraform.lock.hcl │ ├── cloud_function.tf │ ├── locals.tf │ ├── main.tf │ └── variables.tf └── tests/ └── test_weather.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/deploy.yml ================================================ name: Pull Request CD on: push: branches: - main jobs: terraform: name: terraform runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 - name: Terraform id: credentials run: | # Get GCP credentials echo "${KEY}" | base64 -d > ~/key.json export GOOGLE_APPLICATION_CREDENTIALS=~/key.json cd terraform terraform init && terraform validate && terraform apply -auto-approve env: KEY: ${{secrets.SERVICE_ACCOUNT}} GOOGLE_APPLICATION_CREDENTIALS: ~/key.json ================================================ FILE: .github/workflows/pull-request.yml ================================================ name: Pull Request CI on: [pull_request, workflow_dispatch] jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up Python 3.11 uses: actions/setup-python@v3 - name: Install dependencies id: dependencies run: | make dev - name: Unit Test with pytest id: tests run: | make test - name: Linting id: lint run: | make pylint tflint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 name: Checkout source code - uses: actions/cache@v4 name: Cache plugin dir with: path: ~/.tflint.d/plugins key: tflint-${{ hashFiles('.tflint.hcl') }} - uses: terraform-linters/setup-tflint@v4 name: Setup TFLint with: tflint_version: v0.50.3 - name: Show version run: tflint --version - name: Init TFLint run: tflint --init env: # https://github.com/terraform-linters/tflint/blob/master/docs/user-guide/plugins.md#avoiding-rate-limiting GITHUB_TOKEN: ${{ github.token }} - name: Run TFLint run: tflint --chdir=terraform ================================================ FILE: .github/workflows/release.yml ================================================ name: Release to Prod on: release: types: - "released" jobs: terraform: name: terraform runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 - name: Terraform id: credentials run: | # Get GCP credentials echo "${KEY}" | base64 -d > ~/key.json export GOOGLE_APPLICATION_CREDENTIALS=~/key.json cd terraform terraform init && terraform validate terraform workspace new prod || terraform workspace select prod terraform apply -auto-approve env: KEY: ${{secrets.SERVICE_ACCOUNT}} GOOGLE_APPLICATION_CREDENTIALS: ~/key.json ================================================ FILE: .gitignore ================================================ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. #.idea/ .terraform/ terraform/.files/ ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2024 HexCoder Tech Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Makefile ================================================ venv: python3 -m venv .venv echo "Please run 'source .venv/bin/activate'" dev: pip install -r src/api/requirements.txt pip install -r requirements-dev.txt test: PYTHONPATH=src/ pytest tests/ pylint: flake8 src/ tests/ tflint: tflint terraform/ ================================================ FILE: README.md ================================================ # github-actions-demo This repo shows the features of GitHub Actions This sample project requests weather information from the Open Weather API and enables users to request it via HTTP requests. ================================================ FILE: requirements-dev.txt ================================================ pytest==8.1.1 flake8==7.0.0 ================================================ FILE: src/api/main.py ================================================ import functions_framework from flask import abort from weather import get_weather @functions_framework.http def handle_request(request): if request.method == "GET": city = request.args.get("city") if not city: return abort(404, "Please provide a city.") success, response = get_weather(city) if success: return response else: return abort(500, response) else: return abort(403) ================================================ FILE: src/api/requirements.txt ================================================ requests==2.31.0 ================================================ FILE: src/api/weather.py ================================================ import requests api_key = "KEY" def format_weather(city: str, data: dict) -> str: weather = data["weather"][0]["description"] temperature = data["main"]["temp"] return ( f"The weather in {city} is {weather} " f"with a temperature of {temperature} Celcius." ) def get_lat_lon(city): url = ( f"http://api.openweathermap.org/geo/1.0/direct?" f"q={city}&limit=1&appid={api_key}" ) print(f"Retrieving latitude and longitude for {city}.") response = requests.get(url) data = response.json() if response.status_code == 200 and data: lat = data[0]["lat"] lon = data[0]["lon"] return lat, lon else: print("Failed to retrieve latitude and longitude.", data) return None, None def get_weather(city): lat, lon = get_lat_lon(city) if lat is None or lon is None: return False, f"Failed to retrieve weather information for {city}." print(f"Got Lat Lon for {city}: {lat}, {lon}") url = ( f"https://api.openweathermap.org/data/2.5/weather?" f"units=metric&lat={lat}&lon={lon}&appid={api_key}" ) response = requests.get(url) data = response.json() if response.status_code == 200: print(f"Retrieved weather information for {city}.", data) return True, format_weather(city, data) else: print("Failed to retrieve weather information.", data) return False, "Failed to retrieve weather information." if __name__ == "__main__": city = "Munich" print(get_weather(city)) ================================================ FILE: terraform/.terraform.lock.hcl ================================================ # This file is maintained automatically by "terraform init". # Manual edits may be lost in future updates. provider "registry.terraform.io/hashicorp/archive" { version = "2.4.2" hashes = [ "h1:1eOz9vM/55vnQjxk23RhnYga7PZq8n2rGxG+2Vx2s6w=", "zh:08faed7c9f42d82bc3d406d0d9d4971e2d1c2d34eae268ad211b8aca57b7f758", "zh:3564112ed2d097d7e0672378044a69b06642c326f6f1584d81c7cdd32ebf3a08", "zh:53cd9afd223c15828c1916e68cb728d2be1cbccb9545568d6c2b122d0bac5102", "zh:5ae4e41e3a1ce9d40b6458218a85bbde44f21723943982bca4a3b8bb7c103670", "zh:5b65499218b315b96e95c5d3463ea6d7c66245b59461217c99eaa1611891cd2c", "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", "zh:7f45b35a8330bebd184c2545a41782ff58240ed6ba947274d9881dd5da44b02e", "zh:87e67891033214e55cfead1391d68e6a3bf37993b7607753237e82aa3250bb71", "zh:de3590d14037ad81fc5cedf7cfa44614a92452d7b39676289b704a962050bc5e", "zh:e7e6f2ea567f2dbb3baa81c6203be69f9cd6aeeb01204fd93e3cf181e099b610", "zh:fd24d03c89a7702628c2e5a3c732c0dede56fa75a08da4a1efe17b5f881c88e2", "zh:febf4b7b5f3ff2adff0573ef6361f09b6638105111644bdebc0e4f575373935f", ] } provider "registry.terraform.io/hashicorp/google" { version = "5.19.0" hashes = [ "h1:8zAxRX/sRwMky2DwdYV1jJradiK1bAhdk2Yxf3SVWDs=", "zh:10f545f850aadab0da068b9d5023954f2983c4c6acdb999342feb90db373b4b3", "zh:136244af528a17c74e18e83182d96590330a03d7f830c06ae2c9ff4323ebbcf5", "zh:3312be8229c0e4c72f0cae49cbde7a15078793b48d25c5dc0327c5c277475865", "zh:3db97229beb5b3bb586b80756146e16d4f4f8fc60802edd23ac167fd8c10ca07", "zh:764051d375deb983c08c999fc82e622eb68c82bc0361991c3dae7ba6a05dafff", "zh:9309f7140de8394ade88254ff18f2746525143e36d5f4946259097bc0d19dee9", "zh:b8c2e1b837efa3a91e01a06296eb978a11cecf40685664b9d07b2daa6abd5814", "zh:c8a12e2f0daf01e7d9e56b963c9fa64c097a437ed45ffa1ebb2d1db8fd381a00", "zh:d235bbf145d028cb512ad10f4ec5b4e7db3e59c7a862a12fdcbc250173e77ef6", "zh:d997eb3ef64b0e2c99c12aec572d19a5b819edddcdcade8b3b53e3a80d064a9d", "zh:e12dd062d5ad9f8223527de3221ab994a929f47b114f04460f94f11af93d6226", "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", ] } provider "registry.terraform.io/hashicorp/google-beta" { version = "5.19.0" hashes = [ "h1:KQihN6QlyCJQweQV0KdQiU9nlO/9Idejo7j05Q5U1Ho=", "zh:18504b12732d42b818415fd190845732e67cfc64f175ea985fca6378cf46073f", "zh:3c3c2bed588f61301d3a12680a37e5e3863c7e47f23418b658dedad70494d502", "zh:3edf1b797a209486b8d574145eb71034b48d98e5bf9c5afce0dbc04b1d7d46f2", "zh:411297c82d4abdf99128fad94de41d338cc3602f20da9f87fe3c3766bc7cca5e", "zh:8dec9ffbd09073eecd947493633ca8f99951206018625969a380e53002616c82", "zh:d2248af5131d2684a30f99602e7ad930e8287dba1a57669cd319ad0e1596b411", "zh:d9ccd7e8210b6ee122340c747cc84cb94017a6be72115bdd7e9a9056c163dc84", "zh:df1a377c74b2b4a43971ac39f7b983d92ec9ae4f4b81cb86e763630d1ca23e5d", "zh:ea56337757203cb414c00d751b1b9eae28b3d5c0c660fd6b439d0f3597c14cf1", "zh:ec2f17ad4095b6aaa3648ae7b5eb227797a1d2ece70762c3e0cf2696f403536f", "zh:f0938877a10f70cd58d95353b0b4d2c31f6b921a2ebfdc5cec43e127d547c14d", "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", ] } provider "registry.terraform.io/kreuzwerker/docker" { version = "3.0.2" hashes = [ "h1:XjdpVL61KtTsuPE8swok3GY8A+Bu3TZs8T2DOEpyiXo=", "zh:15b0a2b2b563d8d40f62f83057d91acb02cd0096f207488d8b4298a59203d64f", "zh:23d919de139f7cd5ebfd2ff1b94e6d9913f0977fcfc2ca02e1573be53e269f95", "zh:38081b3fe317c7e9555b2aaad325ad3fa516a886d2dfa8605ae6a809c1072138", "zh:4a9c5065b178082f79ad8160243369c185214d874ff5048556d48d3edd03c4da", "zh:5438ef6afe057945f28bce43d76c4401254073de01a774760169ac1058830ac2", "zh:60b7fadc287166e5c9873dfe53a7976d98244979e0ab66428ea0dea1ebf33e06", "zh:61c5ec1cb94e4c4a4fb1e4a24576d5f39a955f09afb17dab982de62b70a9bdd1", "zh:a38fe9016ace5f911ab00c88e64b156ebbbbfb72a51a44da3c13d442cd214710", "zh:c2c4d2b1fd9ebb291c57f524b3bf9d0994ff3e815c0cd9c9bcb87166dc687005", "zh:d567bb8ce483ab2cf0602e07eae57027a1a53994aba470fa76095912a505533d", "zh:e83bf05ab6a19dd8c43547ce9a8a511f8c331a124d11ac64687c764ab9d5a792", "zh:e90c934b5cd65516fbcc454c89a150bfa726e7cf1fe749790c7480bbeb19d387", "zh:f05f167d2eaf913045d8e7b88c13757e3cf595dd5cd333057fdafc7c4b7fed62", "zh:fcc9c1cea5ce85e8bcb593862e699a881bd36dffd29e2e367f82d15368659c3d", ] } ================================================ FILE: terraform/cloud_function.tf ================================================ resource "google_storage_bucket" "cloudfunctions_bucket" { name = join("-", concat(["adopt-a-book-cf-bucket", terraform.workspace])) provider = google location = var.region force_destroy = true } data "archive_file" "weather_service_file" { type = "zip" provider = google-beta output_path = "${path.module}/.files/weather_service.zip" source { content = file("${local.src_dir}/api/main.py") filename = "main.py" } source { content = file("${local.src_dir}/api/weather.py") filename = "weather.py" } source { content = file("${local.src_dir}/api/requirements.txt") filename = "requirements.txt" } } resource "google_storage_bucket_object" "weather_service_zip" { # To ensure the Cloud Function gets redeployed when the zip file is updated. name = format("%s#%s", "weather_service.zip", data.archive_file.weather_service_file.output_md5) bucket = google_storage_bucket.cloudfunctions_bucket.name source = "${path.module}/.files/weather_service.zip" depends_on = [data.archive_file.weather_service_file] } resource "google_cloudfunctions2_function" "weather_service" { name = join("-", concat(["weather-service", terraform.workspace])) description = "Small Cloud Function to get Weather Information" location = var.region build_config { runtime = "python311" entry_point = "handle_request" # Set the entry point source { storage_source { bucket = google_storage_bucket.cloudfunctions_bucket.name object = google_storage_bucket_object.weather_service_zip.name } } } service_config { max_instance_count = 1 available_memory = "256M" timeout_seconds = 60 } depends_on = [google_storage_bucket_object.weather_service_zip] } ================================================ FILE: terraform/locals.tf ================================================ locals { project_root_dir = abspath("${path.root}/..") src_dir = "${local.project_root_dir}/src" } ================================================ FILE: terraform/main.tf ================================================ provider "google" { project = var.project region = var.region } provider "google-beta" { project = var.project region = var.region } terraform { required_version = "1.7.4" backend "gcs" { bucket = "adopt-a-book-terraform-state" prefix = "terraform/edge" } required_providers { google = { source = "hashicorp/google" version = "~> 5.19.0" } google-beta = { source = "hashicorp/google" version = "~> 5.19.0" } } } # Getting the project number for assigning permissions data "google_project" "project" {} data "google_client_config" "default" { depends_on = [data.google_project.project] } resource "google_project_service" "enable_api" { for_each = toset([ "logging.googleapis.com", "artifactregistry.googleapis.com", "run.googleapis.com", "iamcredentials.googleapis.com", ]) service = each.key # value and key are the same for a set timeouts { create = "30m" update = "40m" } disable_on_destroy = false depends_on = [data.google_client_config.default] } ================================================ FILE: terraform/variables.tf ================================================ variable "project" { description = "The GCP project id" default = "adopt-a-book" type = string } variable "region" { description = "The GCP region for this project" default = "europe-west4" type = string } ================================================ FILE: tests/test_weather.py ================================================ from api.weather import format_weather def test_format_weather(): # Test case 1: Sunny weather city = "Los Angeles" data = {"weather": [{"description": "sunny"}], "main": {"temp": 25}} expected = ( "The weather in Los Angeles is sunny " "with a temperature of 25 Celcius." ) assert format_weather(city, data) == expected # Test case 2: Cloudy weather city = "London" data = {"weather": [{"description": "cloudy"}], "main": {"temp": 15}} expected = ( "The weather in London is cloudy " "with a temperature of 15 Celcius." ) assert format_weather(city, data) == expected # Test case 3: Rainy weather city = "Seattle" data = {"weather": [{"description": "rainy"}], "main": {"temp": 10}} expected = ( "The weather in Seattle is rainy " "with a temperature of 10 Celcius." ) assert format_weather(city, data) == expected