diff --git a/.github/workflows/deploy-prd.yaml b/.github/workflows/deploy-prd.yaml new file mode 100644 index 0000000..bf37ba8 --- /dev/null +++ b/.github/workflows/deploy-prd.yaml @@ -0,0 +1,35 @@ +name: Deploy PRD + +on: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.tag.outputs.imageTag}} + steps: + - name: Build process generating a tag + id: tag + run: echo "imageTag=latest" >> $GITHUB_OUTPUT + + deploy: + needs: [build] + runs-on: ubuntu-latest + steps: + - name: Checkout repo + uses: actions/checkout@v4.2.1 + - name: Deploy repo application + uses: stack-spot/cloud-deploy-action@main + id: deploy + with: + CLIENT_REALM: ${{ secrets.CLIENT_REALM_PRD }} + CLIENT_ID: ${{ secrets.CLIENT_ID_PRD }} + CLIENT_KEY: ${{ secrets.CLIENT_KEY_PRD }} + APPLICATION_FILE: ${{ github.workspace }}/stackspot/application-prd.yaml + IMAGE_TAG: ${{needs.build.outputs.tag}} + VERBOSE: true \ No newline at end of file diff --git a/.github/workflows/deploy-stg.yaml b/.github/workflows/deploy-stg.yaml new file mode 100644 index 0000000..6054046 --- /dev/null +++ b/.github/workflows/deploy-stg.yaml @@ -0,0 +1,35 @@ +name: Deploy STG + +on: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.tag.outputs.imageTag}} + steps: + - name: Build process generating a tag + id: tag + run: echo "imageTag=latest" >> $GITHUB_OUTPUT + + deploy: + needs: [build] + runs-on: engineering-runners-stg + steps: + - name: Checkout repo + uses: actions/checkout@v4.2.1 + - name: Deploy repo application + uses: stack-spot/cloud-deploy-action@stg + id: deploy + with: + CLIENT_REALM: ${{ secrets.CLIENT_REALM_STG }} + CLIENT_ID: ${{ secrets.CLIENT_ID_STG }} + CLIENT_KEY: ${{ secrets.CLIENT_KEY_STG }} + APPLICATION_FILE: ${{ github.workspace }}/stackspot/application-stg.yaml + IMAGE_TAG: ${{needs.build.outputs.tag}} + VERBOSE: true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..dddb152 --- /dev/null +++ b/.gitignore @@ -0,0 +1,245 @@ +# Created by https://www.gitignore.io + +### Go ### +# Binaries for programs and plugins +*.dll +*.so +*.dylib + +/dist/ +**/dist/* +/test/tests.* +/test/coverage.* + +# Test binary, built with " go test -c " +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +# Persistent undo +[._]*.un~ + +### VisualStudioCode ### +.vscode/* + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# End of https://www.gitignore.io/api/macos + +# End of https://www.gitignore.io/api/macos +# Intellij project files +*.iml +*.ipr +*.iws +.idea/ + +# Created by https://www.toptal.com/developers/gitignore/api/maven +# Edit at https://www.toptal.com/developers/gitignore?templates=maven + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# End of https://www.toptal.com/developers/gitignore/api/maven + + +# Created by https://www.toptal.com/developers/gitignore/api/java +# Edit at https://www.toptal.com/developers/gitignore?templates=java + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# End of https://www.toptal.com/developers/gitignore/api/java + +# Created by https://www.toptal.com/developers/gitignore/api/node +# Edit at https://www.toptal.com/developers/gitignore?templates=node + +### Node ### +# Logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# Next.js build output +.next + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# End of https://www.toptal.com/developers/gitignore/api/node + +package-lock.json diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..bd4a22a --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 StackSpot + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 5d93fca..c6a740e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,88 @@ # cloud-deploy-action -StackSpot Cloud Github Actions to deploy applications + +GitHub action to authenticate and consume StackSpot Cloud API. + +_**Note**: This action is supported on all runners operating systems (`ubuntu`, `macos`, `windows`)_ + +## 📚 Usage + +### Requirements + +To get the account keys (`CLIENT_ID`, `CLIENT_KEY` and `CLIENT_REALM`), please login using a **ADMIN** user on the [StackSpot Portal](https://stackspot.com), and generate new keys at [https://stackspot.com/en/settings/access-token](https://stackspot.com/en/settings/access-token). + +### Use Case + +```yaml + steps: + - name: Checkout repository + uses: actions/checkout@v4.2.1 + - name: Deploy repo application + uses: stack-spot/cloud-deploy-action@main + id: deploy + with: + CLIENT_REALM: ${{ secrets.CLIENT_REALM }} + CLIENT_ID: ${{ secrets.CLIENT_ID }} + CLIENT_KEY: ${{ secrets.CLIENT_KEY }} + APPLICATION_FILE: ${{ github.workspace }}/stackspot/application.yaml + IMAGE_TAG: latest + VERBOSE: true +``` + +* * * + +## ▶️ Action Inputs + +Field | Mandatory | Default Value | Observation +------------ | ------------ | ------------- | ------------- +**CLIENT_ID** | YES | N/A | [StackSpot](https://stackspot.com/en/settings/access-token) Client ID. +**CLIENT_KEY** | YES | N/A |[StackSpot](https://stackspot.com/en/settings/access-token) Client KEY. +**CLIENT_REALM** | YES | N/A |[StackSpot](https://stackspot.com/en/settings/access-token) Client Realm. +**APPLICATION_FILE** | YES | N/A | StackSpot application config file (generally in `stackspot` folder) +**IMAGE_TAG** | YES | N/A | Image tag to use for deploy +**VERBOSE** | NO | `false` | Whether to show extra logs during execution. (e.g: `true`). + +* * * + +## License + +[Apache License 2.0](https://github.com/stack-spot/cloud-deploy-action/blob/main/LICENSE) + +* * * + +## Development + +### STG environment + +```yaml + steps: + - name: Checkout repository + uses: actions/checkout@v4.2.1 + - name: Deploy repo application + uses: stack-spot/cloud-deploy-action@stg + id: deploy + with: + CLIENT_REALM: ${{ secrets.CLIENT_REALM_STG }} + CLIENT_ID: ${{ secrets.CLIENT_ID_STG }} + CLIENT_KEY: ${{ secrets.CLIENT_KEY_STG }} + APPLICATION_FILE: ${{ github.workspace }}/stackspot/application-stg.yaml + IMAGE_TAG: latest + VERBOSE: true +``` + +### DEV environment + +```yaml + steps: + - name: Checkout repository + uses: actions/checkout@v4.2.1 + - name: Deploy repo application + uses: stack-spot/cloud-deploy-action@dev + id: deploy + with: + CLIENT_REALM: ${{ secrets.CLIENT_REALM_DEV }} + CLIENT_ID: ${{ secrets.CLIENT_ID_DEV }} + CLIENT_KEY: ${{ secrets.CLIENT_KEY_DEV }} + APPLICATION_FILE: ${{ github.workspace }}/stackspot/application-dev.yaml + IMAGE_TAG: latest + VERBOSE: true +``` \ No newline at end of file diff --git a/action.yaml b/action.yaml new file mode 100644 index 0000000..d422a46 --- /dev/null +++ b/action.yaml @@ -0,0 +1,63 @@ +name: 'Cloud Deploy Action' + +description: 'Cloud Deploy Action' + +inputs: + CLIENT_ID: + description: Account client id + required: true + CLIENT_KEY: + description: Account client secret key + required: true + CLIENT_REALM: + description: Account client realm + required: true + VERBOSE: + description: Verbose configuration + required: false + APPLICATION_FILE: + description: Application file path to use + required: true + IMAGE_TAG: + description: Image tag to use + required: true + +runs: + using: "composite" + steps: + - name: Check Runner + run: echo 🤖 OS runner is $(uname) + shell: bash + + - name: Setup Python + uses: actions/setup-python@v5.2.0 + with: + python-version: '3.12' + + - name: Install python libraries + run: pip install requests ruamel-yaml==0.18.6 + shell: bash + + - name: Start StackSpot Cloud Deploy + id: deployment + env: + CLIENT_ID: ${{ inputs.CLIENT_ID }} + CLIENT_KEY: ${{ inputs.CLIENT_KEY }} + CLIENT_REALM: ${{ inputs.CLIENT_REALM }} + VERBOSE: ${{ inputs.VERBOSE }} + APPLICATION_FILE: ${{ inputs.APPLICATION_FILE }} + IMAGE_TAG: ${{ inputs.IMAGE_TAG }} + run: | + if [ ${{runner.os}} != 'Windows' ]; then + python3 ${{ github.action_path }}/deployment.py + elif [ ${{runner.os}} == 'Windows' ]; then + python ${{ github.action_path }}\deployment.py + else + echo "${{runner.os}} not supported" + exit 1 + fi + shell: bash + +branding: + icon: 'terminal' + color: 'gray-dark' \ No newline at end of file diff --git a/deployment.py b/deployment.py new file mode 100644 index 0000000..693301f --- /dev/null +++ b/deployment.py @@ -0,0 +1,228 @@ +import os +import requests +import json +import time +from ruamel.yaml import YAML +from pathlib import Path +from io import StringIO + + +def yaml() -> YAML: + yml = YAML() + yml.indent(mapping=2, sequence=4, offset=2) + yml.allow_unicode = True + yml.default_flow_style = False + yml.preserve_quotes = True + return yml + + +def safe_load(content: str) -> dict: + yml = yaml() + return yml.load(StringIO(content)) + + +# Call to the StackSpot IAM API endpoint to authenticate +def authentication(CLIENT_REALM, CLIENT_ID, CLIENT_KEY): + # Gather authentication data + iam_url = f"https://idm.stackspot.com/{CLIENT_REALM}/oidc/oauth/token" + iam_headers = {'Content-Type': 'application/x-www-form-urlencoded'} + iam_data = {"client_id": f"{CLIENT_ID}", "grant_type": "client_credentials", "client_secret": f"{CLIENT_KEY}"} + + print("⚙️ Authenticating...") + r1 = requests.post( + url=iam_url, + headers=iam_headers, + data=iam_data + ) + + if r1.status_code == 200: + d1 = r1.json() + access_token = d1["access_token"] + print("✅ Successfully authenticated!") + return access_token + else: + print("❌ Error during IAM authentication") + print("- Status:", r1.status_code) + print("- Error:", r1.reason) + print("- Response:", r1.text) + exit(1) + + +# Call to the Cloud Platform API endpoint to start deployment +def deployment(application_name, runtime_name, deploy_headers): + print(f'⚙️ Deploying application "{application_name}" in runtime: "{runtime_name}".') + stackspot_cloud_deployments_url = "https://cloud-cloud-platform-api.prd.stackspot.com/v1/deployments" + r2 = requests.post( + url=stackspot_cloud_deployments_url, + headers=deploy_headers, + data=json_data + ) + + if r2.status_code == 200: + d2 = r2.json() + deployment_id = d2["deploymentId"] + print(f"✅ DEPLOYMENT successfully started with ID: {deployment_id}") + return deployment_id + + else: + print("❌ Error starting cloud deployment") + print("- Status:", r2.status_code) + print("- Error:", r2.reason) + print("- Response:", r2.text) + exit(1) + + +# Call to the Cloud Platform API endpoint to check deployment status +def check_deployment_status(application_name, runtime_name, deployment_id, application_id, deploy_headers): + stackspot_cloud_deployments_details_url = f"https://cloud-cloud-platform-api.prd.stackspot.com/v1/deployments/details/{deployment_id}" + application_portal_url = "https://cloud.prd.stackspot.com/applications" + + i = 0 + while True: + print(f'⚙️ Checking application "{application_name}" deployment status in runtime: "{runtime_name}" ({i}).') + + # Make the request to check the deployment status + r3 = requests.get( + url=stackspot_cloud_deployments_details_url, + headers=deploy_headers + ) + + if r3.status_code == 200: + d3 = r3.json() + deployment_status = d3.get("deploymentStatus") + + # Check if the deployment status is "UP" + if deployment_status == "UP": + print(f'✅ Deployment concluded ({deployment_status}) for application "{application_name}" in runtime: "{runtime_name}".') + print(f"📊 Check the application status on {application_portal_url}/{application_id}/?tabIndex=0") + break # Exit the loop once the status is "UP" + else: + i = i+1 + print(f"⚙️ Current deployment status: {deployment_status}. Retrying in 5 seconds...") + else: + print("- Error getting deployment details") + print("- Status:", r3.status_code) + print("- Error:", r3.reason) + print("- Response:", r3.text) + exit(1) + + # Wait for 5 seconds before the next polling attempt + time.sleep(5) + + +# To use later to extract github url for logs +def build_pipeline_url() -> str: + GITHUB_SERVER_URL = os.getenv("GITHUB_SERVER_URL") + GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY") + GITHUB_RUN_ID = os.getenv("GITHUB_RUN_ID") + if None in [GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID]: + print("- Some mandatory GitHub Action environment variable is empty.") + exit(1) + url = f"{GITHUB_SERVER_URL}/{GITHUB_REPOSITORY}/actions/runs/{GITHUB_RUN_ID}" + return url + +# MAIN EXECUTION +CLIENT_ID = os.getenv("CLIENT_ID") +CLIENT_KEY = os.getenv("CLIENT_KEY") +CLIENT_REALM = os.getenv("CLIENT_REALM") +VERBOSE = os.getenv("VERBOSE") +APPLICATION_FILE = os.getenv("APPLICATION_FILE") +IMAGE_TAG = os.getenv("IMAGE_TAG") + +inputs_list = [CLIENT_ID, CLIENT_KEY, CLIENT_REALM] + +if None in inputs_list: + print("❌ Some credential is missing!") + exit(1) + +# Load the YAML content +with open(Path(APPLICATION_FILE), 'r') as file: + yaml_data = file.read() + +yaml_data = safe_load(yaml_data) + +# Extract and check values from the YAML structure + +if IMAGE_TAG is None: + print("❌ Image Tag to deploy not informed.") + exit(1) +application_name = yaml_data['metadata']['name'] +if application_name is None: + print("❌ Application Name not informed or couldn't be extracted.") + exit(1) +application_id = yaml_data['metadata']['id'] +if application_id is None: + print("❌ Application ID not informed or couldn't be extracted.") + exit(1) +runtime_id = yaml_data['spec']['runtime']['id'] +if runtime_id is None: + print("❌ Runtime ID not informed or couldn't be extracted.") + exit(1) +runtime_name = yaml_data['spec']['runtime']['name'] +image_url = yaml_data['spec']['container']['imageUrl'] +if image_url is None: + print("❌ Image URL not informed or couldn't be extracted.") + exit(1) +container_port = yaml_data['spec']['container']['port'] +if container_port is None: + print("❌ Container Port not informed or couldn't be extracted.") + exit(1) +health_check_path = yaml_data['spec']['container']['healthCheckPath'] +if health_check_path is None: + print("❌ Health Check Path not informed or couldn't be extracted.") + exit(1) +env_vars = yaml_data['spec']['container']['envVars'] +mem = yaml_data['spec']['runtime']['memory'] +if mem is None: + print("❌ Memory not informed or couldn't be extracted.") + exit(1) +cpu = yaml_data['spec']['runtime']['cpu'] +if cpu is None: + print("❌ CPU not informed or couldn't be extracted.") + exit(1) +replica_min = yaml_data['spec']['runtime']['replicaNum']['min'] +if replica_min is None: + print("❌ Replica MIN config not informed or couldn't be extracted.") + exit(1) +replica_max = yaml_data['spec']['runtime']['replicaNum']['max'] +if replica_min is None: + print("❌ Replica MAX config not informed or couldn't be extracted.") + exit(1) +replica_cpu = yaml_data['spec']['runtime']['replicaNum']['cpu'] +if replica_min is None: + print("❌ Replica CPU config not informed or couldn't be extracted.") + exit(1) + +if VERBOSE is not None: + print("🕵️ APPLICATION FILE:", yaml_data) + +# Create the DEPLOYMENT JSON structure +data = { + "applicationId": application_id, + "applicationName": application_name, + "action": "DEPLOY", + "containerPort": f"{container_port}", + "healthCheckPath": health_check_path, + "envVars": env_vars, + "imageUrl": image_url, + "tag": IMAGE_TAG, + "runtimeId": runtime_id, + "mem": mem, + "cpu": cpu, + "replicaNum": { + "min": replica_min, + "max": replica_max, + "cpu": replica_cpu + } +} + +# Convert the dictionary to a JSON string +json_data = json.dumps(data, indent=4) + +if VERBOSE is not None: + print("🕵️ DEPLOYMENT REQUEST DATA:", json_data) + +access_token = authentication(CLIENT_REALM, CLIENT_ID, CLIENT_KEY) +deploy_headers = {"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"} +deployment_id = deployment(application_name, runtime_name, deploy_headers) +check_deployment_status(application_name, runtime_name, deployment_id, application_id, deploy_headers) \ No newline at end of file diff --git a/stackspot/application-prd.yaml b/stackspot/application-prd.yaml new file mode 100644 index 0000000..58fb081 --- /dev/null +++ b/stackspot/application-prd.yaml @@ -0,0 +1,26 @@ +apiVersion: v1 +kind: Application +metadata: + id: 01JAFW10F5VD3JY0254HWP0M4T + name: cloud-apps-demo +spec: + runtime: + id: 01J9C694269APB2TCNAG9CJYVC + name: Runtime 1 + memory: 8 + cpu: 8 + replicaNum: + min: 2 + max: 10 + cpu: 8 + container: + imageUrl: 742799255367.dkr.ecr.sa-east-1.amazonaws.com/cloud-apps-demo + port: 8080 + healthCheckPath: /healthz + envVars: + - key: ENV_VAR_DEMO1 + value: value1 + - key: ENV_VAR_DEMO2 + value: value2 + - key: ENV_VAR_DEMO3 + value: value3 \ No newline at end of file diff --git a/stackspot/application-stg.yaml b/stackspot/application-stg.yaml new file mode 100644 index 0000000..583627c --- /dev/null +++ b/stackspot/application-stg.yaml @@ -0,0 +1,26 @@ +apiVersion: v1 +kind: Application +metadata: + id: 01JAB800C2S97BAZDF2PRDNQD2 + name: cloud-verde +spec: + runtime: + id: 01J9C694269APB2TCNAG9CJYVC + name: Runtime 1 + memory: 8 + cpu: 8 + replicaNum: + min: 2 + max: 10 + cpu: 8 + container: + imageUrl: 300543077521.dkr.ecr.sa-east-1.amazonaws.com/cloud-flask-demo + port: 5000 + healthCheckPath: / + envVars: + - key: ENV_VAR_1 + value: value1 + - key: ENV_VAR_2 + value: value2 + - key: ENV_VAR_3 + value: value3