├── .dockerignore ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml ├── main.workflow └── workflows │ └── main.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── Tiltfile ├── docker-compose.yml ├── kubernetes ├── app.yaml └── ingress.yaml ├── pushdeploy ├── __init__.py ├── apiv1.py └── config.py ├── requirements.txt ├── tests └── setup.yaml ├── version.py └── wsgi.py /.dockerignore: -------------------------------------------------------------------------------- 1 | #Python 2 | __pycache__ 3 | *.pyc 4 | *.pyo 5 | *.pyd 6 | .Python 7 | env 8 | pip-log.txt 9 | pip-delete-this-directory.txt 10 | .tox 11 | .coverage 12 | .coverage.* 13 | .cache 14 | nosetests.xml 15 | coverage.xml 16 | *,cover 17 | *.log 18 | .git 19 | 20 | #Development 21 | Tiltfile 22 | docker-compose.yml 23 | kubernetes 24 | Makefile 25 | README.md 26 | 27 | # Environments 28 | .env 29 | .venv 30 | env/ 31 | venv/ 32 | ENV/ 33 | env.bak/ 34 | venv.bak/ 35 | 36 | # macos 37 | .DS_Store 38 | 39 | # secrets 40 | *secrets* 41 | *credentials* -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | #github: mdgreenwald 4 | ko_fi: mdgreenwald 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior. 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Context (please complete the following information):** 20 | - Kubernetes Version: 21 | - Push-Deploy Version: 22 | 23 | **Additional context** 24 | Add any other context about the problem here. 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: weekly 7 | time: "10:00" 8 | open-pull-requests-limit: 10 9 | reviewers: 10 | - mdgreenwald 11 | labels: 12 | - dependencies 13 | -------------------------------------------------------------------------------- /.github/main.workflow: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: actions/checkout@master 12 | - name: Run a one-line script 13 | run: echo Hello, world! 14 | - name: Run a multi-line script 15 | run: | 16 | echo Add other actions to build, 17 | echo test, and deploy your project. 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | # macos 107 | .DS_Store 108 | 109 | # secrets 110 | *secrets* 111 | *credentials* -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8-alpine 2 | 3 | WORKDIR /opt/push-deploy 4 | 5 | COPY requirements.txt ./ 6 | 7 | RUN pip install --no-cache-dir -r requirements.txt 8 | 9 | COPY . . 10 | 11 | EXPOSE 8000 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: build 2 | 3 | default: build 4 | 5 | help: 6 | @echo "usage: make " 7 | @echo "" 8 | @echo "A set of Makefile commands designed to manipulate the" 9 | @echo "development environment. The default command is 'build', meaning that" 10 | @echo "running 'make' without any arguments is the same as running 'make build'." 11 | @echo "" 12 | @echo "Commands:" 13 | @echo " build" 14 | @echo " Builds the Push-Deploy container." 15 | 16 | build: 17 | @docker build -t push-deploy/latest -f Dockerfile . 18 | 19 | %: 20 | @: 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Push-Deploy 2 | 3 | Push-Deploy is a Python application which helps to securely and simply enable communication between external tools (GitHub Actions, Circle CI, etc…) and Kubernetes without exposing cluster credentials. Instead it exposes an API which accepts parameters. 4 | 5 | Push-deploy is focused on projects which may not have `semver` in place where other tools like [keel.sh](https://keel.sh/) and [weave/flux](https://github.com/fluxcd/flux) would make more sense. 6 | 7 | -- 8 | 9 | ## Disclaimer 10 | 11 | This is pre-release software and is very limited. It will have bugs and lacks many features planned for later releases. The API may also change in ways which are not backwards compatible. 12 | 13 | ## Configuration 14 | 15 | * `PD_REGISTRY`: Registry URI e.g. `258640715359.dkr.ecr.us-west-2.amazonaws.com` 16 | * `PD_SECRET_KEY`: A very long (64+ Char) Alpha Numeric string 17 | * `PD_USER`: Username to authenticate with 18 | * `PD_PASSWORD`: Password to authenticate with 19 | 20 | ## Usage 21 | 22 | ```bash 23 | TOKEN=$( 24 | curl --header "Content-Type: application/json" \ 25 | --request POST \ 26 | -d '{"username":"${USERNAME}","password":"${PASSWORD}"}' \ 27 | https://pushdeploy.domain.com/api/v1/auth 28 | ) 29 | ``` 30 | 31 | ```bash 32 | curl --header "Authorization: Bearer ${TOKEN}" \ 33 | --request POST \ 34 | "https://pushdeploy.domain.com/api/v1/deployment?name=${NAME}&namespace=${NAMESPACE}&image_name=${IMAGE_NAME}&image_tag=${IMAGE_TAG}" 35 | ``` 36 | 37 | ### v1 Endpoints 38 | 39 | - /api/v1/cronjob -> v1beta1/cronjob 40 | - /api/v1/daemonset -> apps/v1/daemonset 41 | - /api/v1/deployment -> apps/v1/deployment 42 | 43 | - /api/v1/deploy -> apps/v1/deployments (**Deprecated**) 44 | 45 | ### v1 Parameters 46 | 47 | - name=name of object 48 | - namespace=namespace of object 49 | - image_name=image name 50 | - image_tag=image tag 51 | 52 | ## Contributing 53 | 54 | #### Dependencies 55 | 56 | **Note:** push-deploy uses `config.load_incluster_config()`and depends on the kubernetes api and thus cannot be meaningfuly run outside of a cluster. 57 | 58 | - Local Docker Daemon 59 | 60 | - Kubernetes Cluster (Remote or local e.g. Docker for Mac Kubernetes, Microk8s, Minikube, etc...) 61 | 62 | - [Tilt](https://tilt.dev/) 63 | 64 | #### Resources 65 | 66 | - [kubernetes-client/python](https://github.com/kubernetes-client/python) 67 | 68 | - [flask](https://flask.palletsprojects.com/) 69 | 70 | - [gunicorn](https://gunicorn.org/) 71 | 72 | #### Usage 73 | 74 | From root: 75 | 76 | ```bash 77 | $ tilt up 78 | ``` 79 | 80 | Tilt will now continuously monitor for changes and rebuild and re-apply. 81 | -------------------------------------------------------------------------------- /Tiltfile: -------------------------------------------------------------------------------- 1 | # one static YAML file 2 | k8s_yaml('./kubernetes/app.yaml') 3 | 4 | docker_build('push-deploy', '.') 5 | 6 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.1" 2 | services: 3 | app: 4 | env_file: 5 | - .env 6 | container_name: push-deploy 7 | image: push-deploy:latest 8 | build: 9 | dockerfile: Dockerfile 10 | context: . 11 | entrypoint: /bin/sh 12 | stdin_open: true 13 | tty: true 14 | restart: always 15 | ports: 16 | - "8000:8000" 17 | volumes: 18 | - "./:/opt/push-deploy" 19 | 20 | -------------------------------------------------------------------------------- /kubernetes/app.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: push-deploy 6 | 7 | --- 8 | apiVersion: v1 9 | kind: ConfigMap 10 | metadata: 11 | name: push-deploy-config 12 | namespace: push-deploy 13 | data: 14 | FLASK_ENV: development 15 | PD_REGISTRY: docker.io 16 | PD_USER: deploy_user 17 | 18 | config.py: | 19 | import os 20 | basedir = os.path.abspath(os.path.dirname(__file__)) 21 | 22 | --- 23 | apiVersion: v1 24 | kind: Secret 25 | metadata: 26 | name: push-deploy-secrets 27 | namespace: push-deploy 28 | type: Opaque 29 | data: 30 | PD_SECRET_KEY: dXNDdUtuclFiU0ZjbkE1eEJjalBKZHFTRGFTQmlrVkFwUmJFT2xtZlhzbDRPQXdSVXZhalVqc2NXNEVjdzZ2Yw== 31 | PD_PASSWORD: cGFzc3dvcmQ= 32 | 33 | --- 34 | apiVersion: v1 35 | kind: ServiceAccount 36 | metadata: 37 | name: push-deploy 38 | namespace: push-deploy 39 | 40 | --- 41 | apiVersion: rbac.authorization.k8s.io/v1beta1 42 | kind: ClusterRole 43 | metadata: 44 | name: deployments-list-patch-clusterrole 45 | namespace: push-deploy 46 | rules: 47 | - apiGroups: ["extensions", "apps"] 48 | resources: ["deployments", "daemonsets"] 49 | verbs: ["list", "patch"] 50 | - apiGroups: ["batch"] 51 | resources: ["cronjobs"] 52 | verbs: ["list", "patch"] 53 | 54 | --- 55 | apiVersion: rbac.authorization.k8s.io/v1beta1 56 | kind: Role 57 | metadata: 58 | name: deployments-list-patch-role 59 | namespace: push-deploy 60 | rules: 61 | - apiGroups: ["extensions", "apps"] 62 | resources: ["deployments", "daemonsets"] 63 | verbs: ["list", "patch"] 64 | - apiGroups: ["batch"] 65 | resources: ["cronjobs"] 66 | verbs: ["list", "patch"] 67 | 68 | --- 69 | apiVersion: rbac.authorization.k8s.io/v1beta1 70 | kind: RoleBinding 71 | metadata: 72 | name: deployments-list-patch-role-binding 73 | namespace: push-deploy 74 | roleRef: 75 | apiGroup: rbac.authorization.k8s.io 76 | kind: Role 77 | name: deployments-list-patch-role 78 | subjects: 79 | - kind: ServiceAccount 80 | name: push-deploy 81 | namespace: push-deploy 82 | 83 | --- 84 | apiVersion: rbac.authorization.k8s.io/v1beta1 85 | kind: ClusterRoleBinding 86 | metadata: 87 | name: deployments-list-patch-clusterrole-binding 88 | roleRef: 89 | apiGroup: rbac.authorization.k8s.io 90 | kind: ClusterRole 91 | name: deployments-list-patch-clusterrole 92 | subjects: 93 | - kind: ServiceAccount 94 | name: push-deploy 95 | namespace: push-deploy 96 | 97 | --- 98 | apiVersion: apps/v1 99 | kind: Deployment 100 | metadata: 101 | name: push-deploy 102 | namespace: push-deploy 103 | spec: 104 | replicas: 1 105 | selector: 106 | matchLabels: 107 | app: push-deploy 108 | template: 109 | metadata: 110 | labels: 111 | app: push-deploy 112 | spec: 113 | serviceAccountName: push-deploy 114 | containers: 115 | - image: push-deploy:latest 116 | imagePullPolicy: IfNotPresent 117 | ports: 118 | - containerPort: 8000 119 | readinessProbe: 120 | tcpSocket: 121 | port: 8000 122 | initialDelaySeconds: 6 123 | periodSeconds: 10 124 | livenessProbe: 125 | httpGet: 126 | path: /health 127 | port: 8000 128 | initialDelaySeconds: 14 129 | periodSeconds: 10 130 | command: ["gunicorn"] 131 | args: ["--workers", "4", "--access-logfile", "-", "--error-logfile", "-", "--bind", "0.0.0.0", "wsgi:app"] 132 | name: push-deploy 133 | envFrom: 134 | - configMapRef: 135 | name: push-deploy-config 136 | - secretRef: 137 | name: push-deploy-secrets 138 | volumeMounts: 139 | - name: config-volume 140 | mountPath: /opt/push-deploy/instance/config.py 141 | subPath: config.py 142 | resources: 143 | requests: 144 | memory: "192Mi" 145 | cpu: "50m" 146 | limits: 147 | memory: "320Mi" 148 | cpu: "250m" 149 | volumes: 150 | - name: config-volume 151 | configMap: 152 | name: push-deploy-config 153 | securityContext: {} 154 | terminationGracePeriodSeconds: 30 155 | 156 | --- 157 | apiVersion: v1 158 | kind: Service 159 | metadata: 160 | name: push-deploy 161 | namespace: push-deploy 162 | labels: 163 | app: push-deploy 164 | spec: 165 | ports: 166 | - port: 80 167 | targetPort: 8000 168 | protocol: TCP 169 | selector: 170 | app: push-deploy 171 | 172 | --- 173 | -------------------------------------------------------------------------------- /kubernetes/ingress.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: extensions/v1beta1 3 | kind: Ingress 4 | metadata: 5 | name: push-deploy 6 | spec: 7 | rules: 8 | - host: push-deploy.internal 9 | http: 10 | paths: 11 | - path: / 12 | backend: 13 | serviceName: push-deploy 14 | servicePort: 80 15 | 16 | --- 17 | -------------------------------------------------------------------------------- /pushdeploy/__init__.py: -------------------------------------------------------------------------------- 1 | from version import __version__ 2 | import os 3 | from kubernetes import client, config 4 | from flask import Flask, jsonify 5 | from flask_jwt_extended import JWTManager, jwt_required, jwt_optional, create_access_token, get_jwt_identity 6 | from pushdeploy import apiv1 7 | 8 | def create_app(test_config=None): 9 | """Create and configure an instance of the Flask application.""" 10 | app = Flask(__name__) 11 | app.config.from_pyfile('config.py') 12 | 13 | app.config['JWT_SECRET_KEY'] = app.config['SECRET_KEY'] 14 | jwt = JWTManager(app) 15 | 16 | @jwt.expired_token_loader 17 | def my_expired_token_callback(expired_token): 18 | token_type = expired_token['type'] 19 | return jsonify({ 20 | 'status': 401, 21 | 'sub_status': 42, 22 | 'msg': 'The {} token has expired'.format(token_type) 23 | }), 401 24 | 25 | if test_config is None: 26 | app.config.from_pyfile("config.py", silent=False) 27 | else: 28 | app.config.update(test_config) 29 | 30 | try: 31 | os.makedirs(app.instance_path) 32 | except OSError: 33 | pass 34 | 35 | @app.route('/health', methods=['GET']) 36 | @jwt_optional 37 | def health(): 38 | return jsonify( 39 | status='healthy', 40 | releaseId=__version__, 41 | ), 200 42 | 43 | @app.route('/', methods=['GET']) 44 | @jwt_required 45 | def index(): 46 | return jsonify(), 200 47 | 48 | app.register_blueprint(apiv1.bp) 49 | 50 | return app 51 | -------------------------------------------------------------------------------- /pushdeploy/apiv1.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import json 3 | from kubernetes import client, config 4 | from datetime import timedelta 5 | from flask import Blueprint, current_app, flash, g, redirect, render_template, request, session, url_for, jsonify 6 | from flask_jwt_extended import JWTManager, jwt_required, jwt_optional, create_access_token, get_jwt_identity 7 | 8 | bp = Blueprint("apiv1", __name__, url_prefix="/api/v1") 9 | 10 | @bp.before_app_request 11 | def init_api(): 12 | """Creates instances of the incluster config and client API 13 | and stores them in global""" 14 | g.configuration = config.load_incluster_config() 15 | g.apps_v1_api_instance = client.AppsV1Api(client.ApiClient(g.configuration)) 16 | g.batch_v1beta1_instance = client.BatchV1beta1Api(client.ApiClient(g.configuration)) 17 | g.PD_REGISTRY = current_app.config['PD_REGISTRY'] 18 | 19 | def list_cron_job(name, namespace): 20 | namespace = "%s" % str(namespace) 21 | name = "metadata.name=%s" % str(name) 22 | api_response = g.batch_v1beta1_instance.list_namespaced_cron_job( 23 | namespace=namespace, 24 | field_selector=name 25 | ) 26 | if len(api_response.items) == 1: 27 | return api_response.items[0] 28 | else: 29 | return "CronJob selector not unique enough." 30 | 31 | def list_daemon_set(name, namespace): 32 | namespace = "%s" % str(namespace) 33 | name = "metadata.name=%s" % str(name) 34 | api_response = g.apps_v1_api_instance.list_namespaced_daemon_set( 35 | namespace=namespace, 36 | field_selector=name 37 | ) 38 | if len(api_response.items) == 1: 39 | return api_response.items[0] 40 | else: 41 | return "DaemonSet selector not unique enough." 42 | 43 | def list_deployment(name, namespace): 44 | namespace = "%s" % str(namespace) 45 | name = "metadata.name=%s" % str(name) 46 | api_response = g.apps_v1_api_instance.list_namespaced_deployment( 47 | namespace=namespace, 48 | field_selector=name 49 | ) 50 | if len(api_response.items) == 1: 51 | return api_response.items[0] 52 | else: 53 | return "Deployment selector not unique enough." 54 | 55 | def patch_cron_job(cron_job_object, image_name, image_tag, name, namespace): 56 | image = "%s/%s:%s" % (g.PD_REGISTRY, image_name, image_tag) 57 | cron_job_object.spec.job_template.spec.template.spec.containers[0].image = image 58 | api_response = g.batch_v1beta1_instance.patch_namespaced_cron_job( 59 | name=name, 60 | namespace=namespace, 61 | body=cron_job_object, 62 | field_manager="push-deploy") 63 | print("CronJob updated. status='%s'" % str(api_response.status)) 64 | 65 | def patch_daemon_set(daemon_set_object, image_name, image_tag, name, namespace): 66 | image = "%s/%s:%s" % (g.PD_REGISTRY, image_name, image_tag) 67 | daemon_set_object.spec.template.spec.containers[0].image = image 68 | api_response = g.apps_v1_api_instance.patch_namespaced_daemon_set( 69 | name=name, 70 | namespace=namespace, 71 | body=daemon_set_object, 72 | field_manager="push-deploy") 73 | print("DaemonSet updated. status='%s'" % str(api_response.status)) 74 | 75 | def patch_deployment(deployment_object, image_name, image_tag, name, namespace): 76 | image = "%s/%s:%s" % (g.PD_REGISTRY, image_name, image_tag) 77 | deployment_object.spec.template.spec.containers[0].image = image 78 | api_response = g.apps_v1_api_instance.patch_namespaced_deployment( 79 | name=name, 80 | namespace=namespace, 81 | body=deployment_object, 82 | field_manager="push-deploy") 83 | print("Deployment updated. status='%s'" % str(api_response.status)) 84 | 85 | @bp.route('/', methods=['GET']) 86 | @jwt_required 87 | def index(): 88 | return jsonify(), 200 89 | 90 | @bp.route('/auth', methods=['POST']) 91 | def login(): 92 | if not request.is_json: 93 | return jsonify({"msg": "Missing JSON in request"}), 400 94 | 95 | username = request.json.get('username', None) 96 | password = request.json.get('password', None) 97 | if not username: 98 | return jsonify({"msg": "Missing username parameter"}), 400 99 | if not password: 100 | return jsonify({"msg": "Missing password parameter"}), 400 101 | 102 | if username != current_app.config['PD_USER'] or password != current_app.config['PD_PASSWORD']: 103 | return jsonify({"msg": "Bad username or password"}), 401 104 | 105 | # Identity can be any data that is json serializable 106 | access_token = create_access_token(identity=username, expires_delta=timedelta(seconds=90)) 107 | return jsonify(access_token=access_token), 200 108 | 109 | @bp.route('/cronjob', methods=['POST']) 110 | @jwt_required 111 | def cronjob(): 112 | image_tag = request.args['image_tag'] 113 | image_name = request.args['image_name'] 114 | name = request.args['name'] 115 | namespace = request.args['namespace'] 116 | cronjob = patch_cron_job( 117 | cron_job_object=list_cron_job(name=name, namespace=namespace), 118 | image_name=image_name, 119 | image_tag=image_tag, 120 | name=name, 121 | namespace=namespace) 122 | return jsonify(msg=cronjob), 201 123 | 124 | @bp.route('/daemonset', methods=['POST']) 125 | @jwt_required 126 | def daemonset(): 127 | image_tag = request.args['image_tag'] 128 | image_name = request.args['image_name'] 129 | name = request.args['name'] 130 | namespace = request.args['namespace'] 131 | daemonset = patch_daemon_set( 132 | daemon_set_object=list_daemon_set(name=name, namespace=namespace), 133 | image_name=image_name, 134 | image_tag=image_tag, 135 | name=name, 136 | namespace=namespace) 137 | return jsonify(msg=daemonset), 201 138 | 139 | @bp.route('/deploy', methods=['GET']) 140 | @jwt_required 141 | def deploy(): 142 | image_tag = request.args['image_tag'] 143 | image_name = request.args['image_name'] 144 | name = request.args['deployment'] 145 | namespace = request.args['namespace'] 146 | deploy = patch_deployment( 147 | deployment_object=list_deployment(name=name, namespace=namespace), 148 | image_name=image_name, 149 | image_tag=image_tag, 150 | name=name, 151 | namespace=namespace) 152 | return jsonify(msg=deploy), 201 153 | 154 | @bp.route('/deployment', methods=['POST']) 155 | @jwt_required 156 | def deployment(): 157 | image_tag = request.args['image_tag'] 158 | image_name = request.args['image_name'] 159 | name = request.args['name'] 160 | namespace = request.args['namespace'] 161 | deployment = patch_deployment( 162 | deployment_object=list_deployment(name=name, namespace=namespace), 163 | image_name=image_name, 164 | image_tag=image_tag, 165 | name=name, 166 | namespace=namespace) 167 | return jsonify(msg=deployment), 201 168 | -------------------------------------------------------------------------------- /pushdeploy/config.py: -------------------------------------------------------------------------------- 1 | import os 2 | basedir = os.path.abspath(os.path.dirname(__file__)) 3 | 4 | PD_REGISTRY = os.environ.get('PD_REGISTRY') 5 | PD_USER = os.environ.get('PD_USER') 6 | PD_PASSWORD = os.environ.get('PD_PASSWORD') 7 | SECRET_KEY = os.environ.get('PD_SECRET_KEY') 8 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | kubernetes==12.0.1 2 | Flask==2.0.1 3 | Flask-API==2.0 4 | flask-jwt-extended==3.25.0 5 | gunicorn==20.0.4 6 | -------------------------------------------------------------------------------- /tests/setup.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: batch/v1beta1 3 | kind: CronJob 4 | metadata: 5 | name: cronjob-test 6 | labels: 7 | environment: test 8 | spec: 9 | schedule: "*/1 * * * *" 10 | concurrencyPolicy: "Forbid" 11 | failedJobsHistoryLimit: 1 12 | successfulJobsHistoryLimit: 1 13 | jobTemplate: 14 | spec: 15 | backoffLimit: 6 16 | ttlSecondsAfterFinished: 30 17 | template: 18 | spec: 19 | containers: 20 | - name: busybox 21 | image: busybox:1.24.0 22 | args: 23 | - /bin/sh 24 | - -c 25 | - date; echo Hello from the Kubernetes cluster 26 | resources: 27 | limits: 28 | cpu: 20m 29 | memory: 32Mi 30 | requests: 31 | cpu: 10m 32 | memory: 16Mi 33 | restartPolicy: OnFailure 34 | 35 | --- 36 | apiVersion: apps/v1 37 | kind: DaemonSet 38 | metadata: 39 | name: daemonset-test 40 | labels: 41 | environment: test 42 | spec: 43 | selector: 44 | matchLabels: 45 | name: daemonset-test 46 | template: 47 | metadata: 48 | labels: 49 | name: daemonset-test 50 | spec: 51 | containers: 52 | - name: busybox 53 | image: busybox:1.24.0 54 | command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"] 55 | resources: 56 | limits: 57 | cpu: 20m 58 | memory: 32Mi 59 | requests: 60 | cpu: 10m 61 | memory: 16Mi 62 | 63 | --- 64 | apiVersion: apps/v1 65 | kind: Deployment 66 | metadata: 67 | name: deployment-test 68 | labels: 69 | environment: test 70 | spec: 71 | selector: 72 | matchLabels: 73 | app: deployment-test 74 | template: 75 | metadata: 76 | labels: 77 | app: deployment-test 78 | spec: 79 | containers: 80 | - name: busybox 81 | image: busybox:1.24.0 82 | command: ['sh', '-c', "until nslookup myservice.$(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace).svc.cluster.local; do echo waiting for myservice; sleep 2; done"] 83 | resources: 84 | limits: 85 | cpu: 20m 86 | memory: 32Mi 87 | requests: 88 | cpu: 10m 89 | memory: 16Mi 90 | -------------------------------------------------------------------------------- /version.py: -------------------------------------------------------------------------------- 1 | 2 | __version__ = '0.0.5' 3 | -------------------------------------------------------------------------------- /wsgi.py: -------------------------------------------------------------------------------- 1 | import os 2 | from werkzeug.middleware.proxy_fix import ProxyFix 3 | from pushdeploy import create_app 4 | 5 | app = ProxyFix(create_app(), x_for=1, x_host=1) 6 | --------------------------------------------------------------------------------