├── .gitattributes ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── MANIFEST.in ├── README.md ├── argocd_app_bootstrap ├── __init__.py ├── _version.py ├── config.yml ├── definitions.py ├── main.py ├── tasks │ ├── argocd │ │ ├── run │ │ │ └── actions.py │ │ └── setup │ │ │ └── actions.py │ ├── common │ │ └── actions.py │ └── deploy │ │ └── setup │ │ └── actions.py ├── templates │ ├── application.yml.j2 │ ├── deploy │ │ ├── Chart.yaml.j2 │ │ ├── deployment.yml.j2 │ │ ├── deployment_patch.yml.j2 │ │ ├── kustomization_base.yml.j2 │ │ ├── kustomization_overlays.yml.j2 │ │ ├── mapping.yml.j2 │ │ ├── namespace.yml.j2 │ │ └── service.yml.j2 │ ├── namespaces.yml.j2 │ └── project.yml.j2 └── utils │ └── common.py ├── build.sh ├── docker ├── Dockerfile ├── argocd-linux-amd64 ├── docker_build.sh └── startup.sh ├── img ├── app_bundle_repo_structure.png └── child_repo_kustomized_helm.png ├── requirements.txt └── setup.py /.gitattributes: -------------------------------------------------------------------------------- 1 | argocd-linux-amd64 filter=lfs diff=lfs merge=lfs -text 2 | -------------------------------------------------------------------------------- /.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 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | 132 | # Misc 133 | data 134 | docker/requirements*.txt 135 | docker/*.whl 136 | docker/*.yml 137 | docker/*.json 138 | scratchpad.sh 139 | .DS_Store 140 | cleanup_child.sh 141 | cleanup_parent.sh 142 | argo_proj.yml 143 | 144 | # iCloud duplicate file >:< 145 | * * 146 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v2.3.0 4 | hooks: 5 | - id: check-yaml 6 | # - id: end-of-file-fixer 7 | # - id: trailing-whitespace 8 | - repo: https://github.com/psf/black 9 | rev: 19.3b0 10 | hooks: 11 | - id: black 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 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Manifest syntax https://docs.python.org/2/distutils/sourcedist.html 2 | 3 | # Use this if using package.py to build distribution (see: https://medium.com/@amimahloof/how-to-package-a-python-project-with-all-of-its-dependencies-for-offline-install-7eb240b27418) 4 | graft wheelhouse 5 | 6 | 7 | recursive-exclude __pycache__ *.pyc *.pyo *.orig 8 | 9 | exclude *.js* 10 | exclude *.git* 11 | exclude *.coveragerc 12 | exclude *.sh 13 | exclude proc* 14 | exclude pylint* 15 | exclude README* 16 | 17 | include requirements*.* 18 | recursive-include argocd_app_bootstrap * 19 | exclude requirements-dev.* 20 | 21 | prune .git 22 | prune venv -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ArgoCD App Bootstrap 2 | 3 | Take the headache out of deploying apps on k8s via ArgoCD with some templating and magic. 4 | 5 | # Pre-Requisites 6 | 7 | To make the most out of this code, you'll need a Kubernetes cluster running ArgoCD. Not sure how to install ArgoCD on your cluster? Check out this handy-dandy tutorial [here](https://medium.com/dzerolabs/installing-ambassador-argocd-and-tekton-on-kubernetes-540aacc983b9). 8 | 9 | You also need to be running Python >=3.8 if you want to run the code locally. Alternatively, you can run the code from within Docker. [Image provided](docker/Dockerfile). Obviously, if you go that route, you'll need to have Docker installed. 10 | 11 | You can check out our other ArgoCD-themed tutorials: 12 | * [Using Tekton and ArgoCD to Set Up a Kubernetes-Native Build & Release Pipeline](https://medium.com/dzerolabs/using-tekton-and-argocd-to-set-up-a-kubernetes-native-build-release-pipeline-cf4f4d9972b0) 13 | * [Configuring SSO with Azure Active Directory on ArgoCD](https://medium.com/dzerolabs/configuring-sso-with-azure-active-directory-on-argocd-d20be4ba753b) 14 | * [Turbocharge ArgoCD with App of Apps Pattern and Kustomized Helm](https://medium.com/dzerolabs/turbocharge-argocd-with-app-of-apps-pattern-and-kustomized-helm-ea4993190e7c) 15 | 16 | # Quickstart 17 | 18 | >NOTE: I am using Fish as my default shell. You'll need to make adjustments in some spots if you're using Bash. 19 | 20 | ## Local Python Setup 21 | 22 | To keep things neat, I like to use Python virtual environments. Set up your virtual environment by running the commands below: 23 | 24 | ```bash 25 | pip install venv 26 | virtualenv venv 27 | source venv/bin/activate.fish 28 | python -m pip install --upgrade pip 29 | pip install --upgrade --force-reinstall -r requirements.txt 30 | ``` 31 | 32 | ### PreCommit Config 33 | 34 | I use `pre-commit` to format my Python code so that it's consistent across the board. It's installed as part of `requirements.txt` 35 | 36 | Once `pre-commit` is installed, run the commands below to set up the tool. 37 | 38 | ```bash 39 | pre-commit install 40 | pre-commit run --all-files 41 | ``` 42 | 43 | ## ArgoCD CLI Installation in a Dockerfile 44 | 45 | Since the ArgoCD CLI installation instructions don't seem to work when building a Dockerfile, I've downloaded a copy of the binary to this repo, which then I copy when building the Dockerfile. Since it's a big file, you need `git-lfs` when adding to the repo. 46 | 47 | To install `git-lfs`: 48 | 49 | ```bash 50 | brew install git-lfs 51 | git lfs install 52 | git lfs track argocd-linux-amd64 53 | ``` 54 | 55 | >NOTE: If you've figured out how to build a Dockerfile with the ArgoCD CLI that's less convoluted than my process, please, SHARE YOUR KNOWLEDGE!! 56 | 57 | ## Install ArgoCD CLI from Your Own API Server 58 | 59 | Fun fact: you can install the ArgoCD CLI from your ArgoCD cluster, rather than from [ArgoCD's GitHub repo](https://argoproj.github.io/argo-cd/cli_installation/). 60 | 61 | One reason why you might choose this route is that it ensures parity between your CLI version and the version running on your k8s cluster. 62 | 63 | Reference: [ArgoCD Docs](https://argoproj.github.io/argo-cd/user-guide/ci_automation/#synchronize-the-app-optional) 64 | 65 | * Mac: `http:///argo-cd/download/argocd-darwin-amd64` 66 | * Windows: `http:///argo-cd/download/argocd-windows-amd64.exe` 67 | * Linux: `http:///argo-cd/download/argocd-linux-amd64` 68 | 69 | ## Run the Code Locally Using Python Invoke 70 | 71 | To run the code locally using Python Invoke: 72 | 73 | >**NOTE:** I'm using Fish as my default shell. Please update accordingly for Bash. 74 | 75 | ```bash 76 | set -x GIT_USERNAME 77 | set -x GIT_TOKEN 78 | set -x GIT_REPO_URL 79 | set -x ARGOCD_USERNAME admin 80 | set -x ARGOCD_PASSWORD 81 | set -x ENV development 82 | set -x TARGET_ENVIRONMENT "DEV" 83 | 84 | # Set up App of Apps YAML 85 | invoke --collection=argocd_app_bootstrap argo-setup.setup-app-of-apps 86 | 87 | # Deploy App Bundle to ArgoCD 88 | invoke --collection=argocd_app_bootstrap argo-run.deploy-app-bundle 89 | 90 | # Cascade delete the ArgoCD App Bundle 91 | invoke --collection=argocd_app_bootstrap argo-run.remove-app-bundle 92 | 93 | # Removes all registered repos and projects from ArgoCD defined in argo_proj.yml 94 | invoke --collection=argocd_app_bootstrap argo-run.remove-project argo-run.remove-repos 95 | 96 | # Kubernetes deployment scaffolding (creates kustomized helm folder and some templated YAMLs) 97 | invoke --collection=argocd_app_bootstrap deploy-setup.bootstrap-k8s-deployment 98 | 99 | ``` 100 | 101 | ## Docker 102 | 103 | To run code within the Docker container, let's first build the Dockerfile:. 104 | 105 | Before running the Docker build, you'll have to do the following: 106 | 1. Modify `Line 45` in the [Dockerfile](docker/Dockerfile) to point to your own gcloud service account credentials JSON file. If you're not on gcloud, please modify the dockerfile accordingly. 107 | 2. Modify `Line 26` in [docker_build.sh](docker/docker_build.sh) to point to your own gcloud service account credentials JSON file. If you're not on gcloud, please modify the script accordingly. 108 | 109 | >**NOTE:** You should check out this [blog post on Medium](https://medium.com/@jryancanty/stop-downloading-google-cloud-service-account-keys-1811d44a97d9) if you want to impersonate a service account instead. Honestly, it's a better idea. I just haven't gotten to it myself. 110 | 111 | Now run the build. 112 | 113 | ```bash 114 | # Build 115 | ./docker/docker_build.sh 116 | ``` 117 | 118 | Run the image: 119 | 120 | ```bash 121 | # Run 122 | docker run -it --rm \ 123 | --network host \ 124 | --name argocd-bootstrap \ 125 | -e ENV="development_docker" \ 126 | -e GIT_USERNAME="" \ 127 | -e GIT_TOKEN="" \ 128 | -e GIT_REPO_URL="" \ 129 | -e ARGOCD_USERNAME="admin" \ 130 | -e ARGOCD_PASSWORD="" \ 131 | -e TARGET_ENVIRONMENT="DEV" \ 132 | argocdapp-bootstrap:1.0.0 "/bin/bash" 133 | ``` 134 | 135 | Once you're inside the container, play around by running the commands below: 136 | 137 | ```bash 138 | # gcloud login, sets up kube config 139 | ./startup.sh 140 | 141 | # Set up App of Apps YAML 142 | argo-bootstrap argo-setup.setup-app-of-apps 143 | 144 | # Deploy App Bundle to ArgoCD 145 | argo-bootstrap argo-run.deploy-app-bundle 146 | 147 | # Cascade delete the ArgoCD App Bundle 148 | argo-bootstrap argo-run.remove-app-bundle 149 | 150 | # Removes all registered repos and projects from ArgoCD defined in argo_proj.yml 151 | argo-bootstrap argo-run.remove-project argo-run.remove-repos 152 | 153 | # Kubernetes deployment scaffolding (creates kustomized helm folder and some templated YAMLs) 154 | argo-bootstrap deploy-setup.bootstrap-k8s-deployment 155 | ``` 156 | 157 | >NOTE: `startup.sh` assumes that you're using `gcloud`. If you're on a different cloud provider, you'll need to modify accordingly. 158 | 159 | # The Tool 160 | 161 | We're into the good stuff now. 162 | 163 | The purpose of this tool is to allow for making it easier to implement ArgoCD's App of Apps pattern. It generates the necessary files and folder structure described in our blog post about the [App of Apps Pattern](https://medium.com/dzerolabs/turbocharge-argocd-with-app-of-apps-pattern-and-kustomized-helm-ea4993190e7c). 164 | 165 | First, have a quick refresher on some useful terms. 166 | 167 | >An **App Bundle** is a group of related microservices. 168 | 169 | >An **App Manifest** refers to all of the YAML definitions that make your microservices run on Kubernetes. For example, a `Service` resource definition and a `Deployment` resource definition. 170 | 171 | This tool reads a file called `argo_proj.yml` to create an `AppProject` YAML and all of the `Application` YAMLs for the microservices being grouped together for a particular App Bundle. Keeping in mind that applications are often deployed to different environments, these files are created for `DEV`, `QA`, and `PROD` environments. 172 | 173 | The `argo_proj.yml` looks something like this: 174 | 175 | ```yaml 176 | argocd: 177 | project: 178 | name: appbundle-project 179 | description: The app bundle POC project 180 | parent_app: 181 | name: appbundle 182 | repo_url: https://github.com/d0-labs/argocd-app-of-apps-parent 183 | version: 1.0 184 | child_apps: 185 | destination_cluster: in-cluster 186 | app: 187 | - name: helm-guestbook 188 | repo_url: https://github.com/d0-labs/argocd-app-of-apps-child-guestbook 189 | namespace: helm-guestbook 190 | manifest_path: kustomized_helm/overlays/dev 191 | deploy_plugin: kustomized-helm 192 | - name: 2048-game 193 | repo_url: https://github.com/d0-labs/argocd-app-of-apps-child-2048-game 194 | namespace: 2048-game 195 | manifest_path: kustomized_helm/overlays/dev 196 | deploy_plugin: kustomized-helm 197 | ``` 198 | 199 | * `parent_app.repo_url`: The App Bundle repo. This is the repo in which the `Application` and `AppProject` YAML files will be created. This repo would be typically managed by an SRE team. 200 | * `child_apps.destination_cluster`: The cluster to which the microservices apps will be deployed 201 | * `app.repo_url`: The application repo in which the application code resides. This is typically managed by application developers. 202 | * `app.manifest_path`: The location of the Kubernetes app manifests (i.e. Helm Charts, Kustomizations, `Service` definitions, `Deployment` definitions, etc.) 203 | * `app.deploy_plugin`: The name of the [ArgoCD plugin](https://argoproj.github.io/argo-cd/user-guide/config-management-plugins/) to use, as configured in the [argocd-cm.yml](https://gist.github.com/avillela/c2abb14b1f03e3090eb08e55aca7cccc#file-customized-helm-argocd-cm-yml) file. We are assuming the use of a [kustomized-helm plugin](https://gist.github.com/avillela/c2abb14b1f03e3090eb08e55aca7cccc#file-customized-helm-argocd-cm-yml). If this field is ommitted, then ArgoCD will look for either Helm Charts, Kustomizations, or plain old YAML in the specified manifest path. 204 | 205 | ## What can you do with it? 206 | 207 | So you've seen the main commands of the tool in the quickstart guide above. Here's a more detailed view of what they do. 208 | 209 | Please note that I am assuming that you've got your ArgoCD up and running and configured, and have registered your clusters using `argocd cluster add`. For more on ArgoCD setup, please check out [this blog post](https://medium.com/dzerolabs/using-tekton-and-argocd-to-set-up-a-kubernetes-native-build-release-pipeline-cf4f4d9972b0). 210 | 211 | ### argo-bootstrap argo-setup.setup-app-of-apps 212 | 213 | This action creates the `Application` and `AppProject` YAML files for the parent and child applications defined in the App Bundle repo. The files are created in the App Bundle repo (like [this one](https://github.com/d0-labs/argocd-app-of-apps-parent)), and have a file structure like this one: 214 | 215 | ![image](img/app_bundle_repo_structure.png) 216 | 217 | Note how we're creating app bundles for 3 different k8s clusters (`DEV`, `QA`, `PROD`). 218 | 219 | ### argo-run.deploy-app-bundle 220 | 221 | This action will: 222 | * Register the repos associated with the parent and child apps defined in `argo_proj.yml`. 223 | * Create the `AppProject` in ArgoCD for the target environment (i.e. either `DEV`, `QA`, or `PROD`). Remember that `TARGET_ENVIRONMENT` environment variable that you set in the Quickstart above? :) 224 | * Create the parent and child `Application` in ArgoCD 225 | * Deploy the applications to the target cluster for the given target environment (defined by `TARGET_ENVIRONMENT`) 226 | 227 | ### argo-run.remove-app-bundle 228 | 229 | This action will perform a cascade delete of all parent and child resources, including app manifests, namespaces, and ArgoCD `Application` definitions. It does NOT delete the project or repo registrations. 230 | 231 | ### argo-run.remove-project argo-run.remove-repos 232 | 233 | This action is actually 2 chained actions. The first action deletes the `AppProject` from ArgoCD. The second action unregisters the repos configured in `argo_proj.yml`. 234 | 235 | You could technically create a single `invoke` task which chains them together without having to "manually" chain them as above. 236 | 237 | ### deploy-setup.bootstrap-k8s-deployment 238 | 239 | This action will scaffold a folder structure for deploying applications to Kubernetes using [Kustomized Helm](https://jfrog.com/blog/power-up-helm-charts-using-kustomize-to-manage-kubernetes-deployments/). The folder structure looks like this: 240 | 241 | ![image](img/child_repo_kustomized_helm.png) 242 | 243 | Helm is used to template base variables (i.e. `.Release.Name`). 244 | 245 | Kustomize is used to: 246 | * Apply common namespace and labels to all YAML resources being Kustomized 247 | * Handle environment-specific configuratoins (i.e. DEV, QA, PROD). This includes: 248 | * Number of replicas for the `Deployment` (via `patchesJson6902` in the `kustomization.yml`) 249 | * Number of seconds for the livenessProbe for the `Deployment` (via `patchesJson6902` in the `kustomization.yml`) 250 | * Image name and tag (via `images` in the `kustomization.yml`) 251 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | # Invoke magic 6 | from invoke import Collection, task 7 | 8 | import argocd_app_bootstrap.tasks.common.actions as common_actions 9 | import argocd_app_bootstrap.tasks.argocd.setup.actions as argo_setup_actions 10 | import argocd_app_bootstrap.tasks.argocd.run.actions as argo_un_actions 11 | import argocd_app_bootstrap.tasks.deploy.setup.actions as scaffold_actions 12 | 13 | ns = Collection( 14 | common=common_actions, 15 | argo_setup=argo_setup_actions, 16 | argo_run=argo_un_actions, 17 | deploy_setup=scaffold_actions, 18 | ) 19 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/_version.py: -------------------------------------------------------------------------------- 1 | # Single version file for everyone, swiped from pyinvoke. Check out the following resources on pyinvoke's GitHub repo: 2 | # https://github.com/pyinvoke/invoke/blob/master/invoke/__init__.py 3 | # https://github.com/pyinvoke/invoke/blob/master/invoke/_version.py 4 | # https://github.com/pyinvoke/invoke/blob/master/setup.py 5 | 6 | __version__ = "0.1.0" 7 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/config.yml: -------------------------------------------------------------------------------- 1 | 2 | defaults: &defaults 3 | name: ArgoCD App Bootstrap 4 | git-provider: github.com 5 | argocd-admin-email: sre@you.com 6 | environments: 7 | - dev 8 | - qa 9 | - prod 10 | 11 | development: 12 | <<: *defaults 13 | argocd: 14 | host: localhost 15 | port: 8080 16 | insecure: true 17 | 18 | development_docker: 19 | <<: *defaults 20 | argocd: 21 | host: host.docker.internal 22 | port: 8080 23 | insecure: true 24 | 25 | qa: 26 | <<: *defaults 27 | argocd: 28 | host: localhost 29 | port: 8080 30 | insecure: true 31 | 32 | production: 33 | <<: *defaults 34 | argocd: 35 | host: localhost 36 | port: 8080 37 | insecure: true 38 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/definitions.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | from ruamel.yaml import YAML 6 | 7 | 8 | yaml = YAML() 9 | 10 | ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) 11 | 12 | # Sets default environment to development, unless env is explicityly set 13 | if os.environ.get("ENV") is None: 14 | os.environ["ENV"] = "development" 15 | 16 | # Set default behaviour to grab argo_proj.yml from version control 17 | if os.environ.get("USE_LOCAL_ARGO_PROJ") is None: 18 | os.environ["USE_LOCAL_ARGO_PROJ"] = "false" 19 | 20 | with open(os.path.join(ROOT_DIR, "config.yml"), "r") as stream: 21 | try: 22 | configs = yaml.load(stream) 23 | APP_CONFIG = configs[os.environ.get("ENV")] 24 | except Exception as error: 25 | print(error) 26 | 27 | 28 | TEMPLATES_PATH = os.path.join(ROOT_DIR, "templates") 29 | DEPLOY_TEMPLATES_PATH = os.path.join(TEMPLATES_PATH, "deploy") 30 | DATA_PATH = os.path.join(ROOT_DIR, "data") 31 | 32 | # ArgoCD app folder structure 33 | ARGOCD_DIR = "argocd" 34 | NAMESPACES_DIR = "namespaces" 35 | PROJECTS_DIR = "projects" 36 | APPS_PARENT_DIR = "apps-parent" 37 | APPS_CHILDREN_DIR = "apps-children" 38 | 39 | PARENT_REPO_PATH = os.path.join(DATA_PATH, "parent_repo") 40 | ARGOCD_PATH = os.path.join(PARENT_REPO_PATH, ARGOCD_DIR) 41 | NAMESPACES_PATH = os.path.join(ARGOCD_PATH, NAMESPACES_DIR) 42 | PROJECTS_PATH = os.path.join(ARGOCD_PATH, PROJECTS_DIR) 43 | APPS_PARENT_PATH = os.path.join(ARGOCD_PATH, APPS_PARENT_DIR) 44 | APPS_CHILDREN_PATH = os.path.join(ARGOCD_PATH, APPS_CHILDREN_DIR) 45 | 46 | ROOT_APP = "root-app" 47 | ARGO_PROJ_YAML = "argo_proj.yml" 48 | 49 | ARGOCD_ROOT = "argocd" 50 | 51 | # App deployment folder structure (Helm + Kustomize) 52 | CHILD_REPOS_PATH = os.path.join(DATA_PATH, "child_repos") 53 | KUSTOMIZED_HELM_PATH = os.path.join(CHILD_REPOS_PATH, "kustomized_helm") 54 | HELM_BASE_PATH = os.path.join(KUSTOMIZED_HELM_PATH, "helm_base") 55 | HELM_TEMPLATES_PATH = os.path.join(HELM_BASE_PATH, "templates") 56 | 57 | OVERLAYS_PATH = os.path.join(KUSTOMIZED_HELM_PATH, "overlays") 58 | 59 | PATCH_DIR = "patch" 60 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/main.py: -------------------------------------------------------------------------------- 1 | from . import * 2 | 3 | from ._version import __version__ 4 | from invoke import Program 5 | 6 | 7 | version = __version__ 8 | 9 | program = Program( 10 | name="ArgoCD App Bootstrap", 11 | namespace=ns, 12 | version=version, 13 | binary="argo-bootstrap", 14 | binary_names=["argo-bootstrap"], 15 | ) 16 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/tasks/argocd/run/actions.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | 6 | from invoke import task 7 | from invoke.tasks import Task 8 | 9 | import argocd_app_bootstrap.tasks.common.actions as common_actions 10 | import argocd_app_bootstrap.tasks.argocd.setup.actions as setup 11 | 12 | from argocd_app_bootstrap.definitions import ( 13 | APPS_PARENT_PATH, 14 | ARGOCD_PATH, 15 | PROJECTS_PATH, 16 | ROOT_APP, 17 | yaml, 18 | ) 19 | 20 | from argocd_app_bootstrap.utils import common 21 | from argocd_app_bootstrap.utils.common import LOG_ERROR, LOG_INFO, LOG_WARN, publish 22 | 23 | ## ------------------ 24 | 25 | 26 | @task() 27 | def register_repos(ctxt): 28 | """ 29 | Register the repos in ArgoCD that are specified in the argo_proj.yml. 30 | 31 | ** This is a helper task and should not be called on its own. 32 | """ 33 | 34 | task_desc = "Registering repos with ArgoCD" 35 | publish(f"START: {task_desc}", LOG_INFO) 36 | 37 | try: 38 | 39 | if "argo_proj_yaml" not in ctxt: 40 | raise Exception("Missing app config") 41 | 42 | repos_list = common.get_repos(ctxt) 43 | git_username = ( 44 | ctxt.config["git_username"] 45 | if ctxt.config["git_username"] is not None 46 | else "blah" 47 | ) 48 | for repo_url in repos_list: 49 | common.run_command( 50 | ctxt, 51 | f"argocd repo add {repo_url} --username {git_username} --password {ctxt.config['git_token']}", 52 | ) 53 | 54 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 55 | 56 | except Exception as e: 57 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 58 | raise e 59 | 60 | 61 | ## ------------------ 62 | 63 | 64 | @task() 65 | def apply_and_sync(ctxt): 66 | """ 67 | Deploy the ArgoCD "App of Apps" manifests to Kubernetes, and sync all related apps. 68 | 69 | ** This is a helper task and should not be called on its own. 70 | """ 71 | 72 | environment = ctxt["target_environment"] 73 | task_desc = f"Creating app of apps in ArgoCD for [{environment}] environment" 74 | publish(f"START: {task_desc}", LOG_INFO) 75 | 76 | try: 77 | 78 | # Create ArgoCD project 79 | common.run_command( 80 | ctxt, f"kubectl apply -f {PROJECTS_PATH}/project-{environment}.yml" 81 | ) 82 | 83 | # Apply and sync master app 84 | with open(f"{ARGOCD_PATH}/{ROOT_APP}-{environment}.yml", "r") as stream: 85 | root_app_yaml = yaml.load(stream) 86 | root_app_name = root_app_yaml["metadata"]["name"] 87 | 88 | common.run_command( 89 | ctxt, f"kubectl apply -f {ARGOCD_PATH}/{ROOT_APP}-{environment}.yml" 90 | ) 91 | common.run_command(ctxt, f"argocd app sync {root_app_name}") 92 | 93 | parent_app_name = f'{ctxt["argo_proj_yaml"]["argocd"]["parent_app"]["name"]}-app-{environment}' 94 | 95 | common.run_command( 96 | ctxt, 97 | f"argocd app sync -l app.kubernetes.io/instance=root-{parent_app_name}", 98 | ) 99 | 100 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 101 | 102 | except Exception as e: 103 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 104 | raise e 105 | 106 | 107 | ## ------------------ 108 | 109 | 110 | @task() 111 | def delete_repos(ctxt): 112 | 113 | task_desc = "Deleting repos" 114 | publish(f"START: {task_desc}", LOG_INFO) 115 | 116 | try: 117 | 118 | if "argo_proj_yaml" not in ctxt: 119 | raise Exception("Missing app config") 120 | 121 | repos_list = common.get_repos(ctxt) 122 | for repo_url in repos_list: 123 | publish(f"INFO: Removing repo [{repo_url}]", LOG_INFO) 124 | result = common.run_command( 125 | ctxt, f"argocd repo rm {repo_url}", raise_exception_on_err=False 126 | ) 127 | 128 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 129 | 130 | except Exception as e: 131 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 132 | raise e 133 | 134 | 135 | ## ------------------ 136 | 137 | 138 | @task() 139 | def delete_project(ctxt, target_environment=os.environ.get("TARGET_ENVIRONMENT")): 140 | 141 | environment = ctxt["target_environment"] 142 | task_desc = "Deleting project" 143 | publish(f"START: {task_desc}", LOG_INFO) 144 | 145 | try: 146 | 147 | # Apply and sync master app 148 | with open(f"{PROJECTS_PATH}/project-{environment}.yml", "r") as stream: 149 | project_yaml = yaml.load(stream) 150 | project_name = project_yaml["metadata"]["name"] 151 | 152 | common.run_command(ctxt, f"argocd proj delete {project_name}") 153 | 154 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 155 | 156 | except Exception as e: 157 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 158 | raise e 159 | 160 | 161 | ## ------------------ 162 | 163 | 164 | @task() 165 | def delete_apps(ctxt): 166 | """ 167 | Destroy the ArgoCD root-app and all its associated child apps and objects (e.g. namespaces). 168 | This is a cascade delete. 169 | 170 | ** This is a helper task and should not be called on its own. 171 | """ 172 | 173 | environment = ctxt["target_environment"] 174 | task_desc = f"Deleting [root-app-{environment}]. This will delete all related apps and objects" 175 | publish(f"START: {task_desc}", LOG_INFO) 176 | 177 | try: 178 | 179 | # Get the app name 180 | with open(f"{ARGOCD_PATH}/{ROOT_APP}-{environment}.yml", "r") as stream: 181 | root_app_yaml = yaml.load(stream) 182 | root_app_name = root_app_yaml["metadata"]["name"] 183 | 184 | common.run_command(ctxt, f"argocd app delete {root_app_name}") 185 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 186 | 187 | except Exception as e: 188 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 189 | raise e 190 | 191 | 192 | ## ------------------ 193 | 194 | 195 | @task( 196 | help={ 197 | "git-username": "Git username (optional for some Git providers)", 198 | "git-token": "Git personal access token", 199 | "git-repo-url": "Git repo HTTPS URL of the repo where the ArgoCD app definitions are located", 200 | "argocd-username": "ArgoCD username. Must be a local ArgoCD account (e.g. admin). Does not work with SSO.", 201 | "argocd-password": "ArgoCD password. Must be a local ArgoCD account. Does not work with SSO.", 202 | "target-environment": "Target environment to deploy to", 203 | }, 204 | pre=[common_actions.cleanup_data_dir], 205 | post=[ 206 | common_actions.clone_repo, 207 | common_actions.argocd_login, 208 | register_repos, 209 | apply_and_sync, 210 | ], 211 | ) 212 | def deploy_app_bundle( 213 | ctxt, 214 | git_username=os.environ.get("GIT_USERNAME"), 215 | git_token=os.environ.get("GIT_TOKEN"), 216 | git_repo_url=os.environ.get("GIT_REPO_URL"), 217 | argocd_username=os.environ.get("ARGOCD_USERNAME"), 218 | argocd_password=os.environ.get("ARGOCD_PASSWORD"), 219 | target_environment=os.environ.get("TARGET_ENVIRONMENT"), 220 | ): 221 | """ 222 | Deploy the ArgoCD "App of Apps" manifests to Kubernetes, and sync all related apps. 223 | 224 | Arguments can be passed in through the command line, or they can be set as the following environment variables: 225 | 226 | * GIT_USERNAME 227 | * GIT_TOKEN 228 | * GIT_REPO_URL 229 | * ARGOCD_USERNAME 230 | * ARGOCD_PASSWORD 231 | * TARGET_ENVIRONMENT 232 | """ 233 | 234 | common.init_bootstrap( 235 | ctxt, 236 | git_username, 237 | git_token, 238 | git_repo_url, 239 | argocd_username, 240 | argocd_password, 241 | target_environment=target_environment, 242 | ) 243 | 244 | 245 | ## ------------------ 246 | 247 | 248 | @task( 249 | help={ 250 | "git-username": "Git username (optional for some Git providers)", 251 | "git-token": "Git personal access token", 252 | "git-repo-url": "Git repo HTTPS URL of the repo where the ArgoCD app definitions are located", 253 | "argocd-username": "ArgoCD username. Must be a local ArgoCD account (e.g. admin). Does not work with SSO.", 254 | "argocd-password": "ArgoCD password. Must be a local ArgoCD account. Does not work with SSO.", 255 | "target-environment": "Target environment to deploy to", 256 | }, 257 | pre=[common_actions.cleanup_data_dir], 258 | post=[common_actions.clone_repo, common_actions.argocd_login, delete_apps], 259 | ) 260 | def remove_app_bundle( 261 | ctxt, 262 | git_username=os.environ.get("GIT_USERNAME"), 263 | git_token=os.environ.get("GIT_TOKEN"), 264 | git_repo_url=os.environ.get("GIT_REPO_URL"), 265 | argocd_username=os.environ.get("ARGOCD_USERNAME"), 266 | argocd_password=os.environ.get("ARGOCD_PASSWORD"), 267 | target_environment=os.environ.get("TARGET_ENVIRONMENT"), 268 | ): 269 | """ 270 | Remove the ArgoCD root-app and all its associated child apps and objects (e.g. namespaces). 271 | This is a cascade delete. 272 | 273 | Arguments can be passed in through the command line, or they can be set as the following environment variables: 274 | 275 | * GIT_USERNAME 276 | * GIT_TOKEN 277 | * GIT_REPO_URL 278 | * ARGOCD_USERNAME 279 | * ARGOCD_PASSWORD 280 | * TARGET_ENVIRONMENT 281 | """ 282 | 283 | common.init_bootstrap( 284 | ctxt, 285 | git_username, 286 | git_token, 287 | git_repo_url, 288 | argocd_username, 289 | argocd_password, 290 | target_environment=target_environment, 291 | ) 292 | 293 | 294 | ## ------------------ 295 | 296 | 297 | @task( 298 | help={ 299 | "git-username": "Git username (optional for some Git providers)", 300 | "git-token": "Git personal access token", 301 | "git-repo-url": "Git repo HTTPS URL of the repo where the ArgoCD app definitions are located", 302 | "argocd-username": "ArgoCD username. Must be a local ArgoCD account (e.g. admin). Does not work with SSO.", 303 | "argocd-password": "ArgoCD password. Must be a local ArgoCD account. Does not work with SSO.", 304 | "target-environment": "Target environment to deploy to", 305 | }, 306 | pre=[common_actions.cleanup_data_dir], 307 | post=[common_actions.clone_repo, common_actions.argocd_login, delete_project], 308 | ) 309 | def remove_project( 310 | ctxt, 311 | git_username=os.environ.get("GIT_USERNAME"), 312 | git_token=os.environ.get("GIT_TOKEN"), 313 | git_repo_url=os.environ.get("GIT_REPO_URL"), 314 | argocd_username=os.environ.get("ARGOCD_USERNAME"), 315 | argocd_password=os.environ.get("ARGOCD_PASSWORD"), 316 | target_environment=os.environ.get("TARGET_ENVIRONMENT"), 317 | ): 318 | """ 319 | Remove the specified project from ArgoCD. 320 | 321 | Arguments can be passed in through the command line, or they can be set as the following environment variables: 322 | 323 | * GIT_USERNAME 324 | * GIT_TOKEN 325 | * GIT_REPO_URL 326 | * ARGOCD_USERNAME 327 | * ARGOCD_PASSWORD 328 | * TARGET_ENVIRONMENT 329 | """ 330 | 331 | common.init_bootstrap( 332 | ctxt, 333 | git_username, 334 | git_token, 335 | git_repo_url, 336 | argocd_username, 337 | argocd_password, 338 | target_environment=target_environment, 339 | ) 340 | 341 | 342 | ## ------------------ 343 | 344 | 345 | @task( 346 | help={ 347 | "git-username": "Git username (optional for some Git providers)", 348 | "git-token": "Git personal access token", 349 | "git-repo-url": "Git repo HTTPS URL of the repo where the ArgoCD app definitions are located", 350 | "argocd-username": "ArgoCD username. Must be a local ArgoCD account (e.g. admin). Does not work with SSO.", 351 | "argocd-password": "ArgoCD password. Must be a local ArgoCD account. Does not work with SSO.", 352 | }, 353 | pre=[common_actions.cleanup_data_dir], 354 | post=[common_actions.clone_repo, common_actions.argocd_login, delete_repos], 355 | ) 356 | def remove_repos( 357 | ctxt, 358 | git_username=os.environ.get("GIT_USERNAME"), 359 | git_token=os.environ.get("GIT_TOKEN"), 360 | git_repo_url=os.environ.get("GIT_REPO_URL"), 361 | argocd_username=os.environ.get("ARGOCD_USERNAME"), 362 | argocd_password=os.environ.get("ARGOCD_PASSWORD"), 363 | ): 364 | """ 365 | Remove repos from ArgoCD that are specified in argo_proj.yml. 366 | 367 | Arguments can be passed in through the command line, or they can be set as the following environment variables: 368 | 369 | * GIT_USERNAME 370 | * GIT_TOKEN 371 | * GIT_REPO_URL 372 | * ARGOCD_USERNAME 373 | * ARGOCD_PASSWORD 374 | """ 375 | 376 | common.init_bootstrap( 377 | ctxt, git_username, git_token, git_repo_url, argocd_username, argocd_password 378 | ) 379 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/tasks/argocd/setup/actions.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import os, copy 5 | 6 | from jinja2 import Environment, FileSystemLoader, environment 7 | from invoke import task, exceptions 8 | from pathlib import Path 9 | 10 | from argocd_app_bootstrap.definitions import ( 11 | APPS_PARENT_DIR, 12 | APPS_CHILDREN_DIR, 13 | APP_CONFIG, 14 | ARGOCD_DIR, 15 | DATA_PATH, 16 | NAMESPACES_PATH, 17 | PARENT_REPO_PATH, 18 | ARGOCD_PATH, 19 | APPS_PARENT_PATH, 20 | APPS_CHILDREN_PATH, 21 | TEMPLATES_PATH, 22 | PROJECTS_PATH, 23 | ARGO_PROJ_YAML, 24 | ARGOCD_ROOT, 25 | yaml, 26 | ) 27 | 28 | import argocd_app_bootstrap.tasks.common.actions as common_actions 29 | from argocd_app_bootstrap.utils import common 30 | from argocd_app_bootstrap.utils.common import LOG_ERROR, LOG_INFO, LOG_WARN, publish 31 | 32 | 33 | ## ------------------ 34 | 35 | 36 | @task() 37 | def create_folder_structure(ctxt): 38 | """ 39 | Create the folder structure required by the "App of Apps" pattern. 40 | 41 | ** This is a helper task and should not be called on its own. 42 | """ 43 | 44 | task_desc = "Create app of apps folder structure" 45 | publish(f"START: {task_desc}", LOG_INFO) 46 | 47 | try: 48 | if "argo_proj_yaml" not in ctxt: 49 | raise Exception("Missing app config") 50 | 51 | for environment in APP_CONFIG["environments"]: 52 | parent_app = ctxt["argo_proj_yaml"]["argocd"]["parent_app"]["name"] 53 | Path(f"{PROJECTS_PATH}").mkdir(parents=True, exist_ok=True) 54 | Path(os.path.join(APPS_CHILDREN_PATH, environment)).mkdir( 55 | parents=True, exist_ok=True 56 | ) 57 | 58 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 59 | 60 | except Exception as e: 61 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 62 | raise e 63 | 64 | 65 | ## ------------------ 66 | 67 | 68 | @task() 69 | def create_project_yaml(ctxt): 70 | """ 71 | Create the project.yml ArgoCD AppProject file associated with this app. Each app will be in its own project. 72 | 73 | ** This is a helper task and should not be called on its own. 74 | """ 75 | 76 | task_desc = "Create project.yml" 77 | publish(f"START: {task_desc}", LOG_INFO) 78 | 79 | try: 80 | if "argo_proj_yaml" not in ctxt: 81 | raise Exception("Missing app config") 82 | 83 | for environment in APP_CONFIG["environments"]: 84 | project_name = ( 85 | f'{ctxt["argo_proj_yaml"]["argocd"]["project"]["name"]}-{environment}' 86 | ) 87 | project_description = ctxt["argo_proj_yaml"]["argocd"]["project"][ 88 | "description" 89 | ] 90 | 91 | env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), trim_blocks=True) 92 | 93 | rendered_data = env.get_template(f"project.yml.j2").stream( 94 | project_name=project_name, project_description=project_description 95 | ) 96 | 97 | rendered_data.dump(f"{PROJECTS_PATH}/project-{environment}.yml") 98 | 99 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 100 | 101 | except Exception as e: 102 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 103 | raise e 104 | 105 | 106 | ## ------------------ 107 | 108 | 109 | @task() 110 | def create_root_app_yaml(ctxt): 111 | """ 112 | Create the root-app.yml ArgoCD Application file definition. 113 | 114 | ** This is a helper task and should not be called on its own. 115 | 116 | """ 117 | 118 | environment = ctxt["environment"] 119 | task_desc = f"Create root-app-{environment}.yml" 120 | publish(f"START: {task_desc}", LOG_INFO) 121 | 122 | try: 123 | if "argo_proj_yaml" not in ctxt: 124 | raise Exception("Missing app config") 125 | 126 | app_of_apps = copy.deepcopy(ctxt["argo_proj_yaml"]["argocd"]) 127 | 128 | root_app = { 129 | "name": f"root-{app_of_apps['parent_app']['name']}", 130 | "filename": f"root-app-{environment}.yml", 131 | # "manifest_path": f"{ARGOCD_DIR}/{APPS_PARENT_DIR}/{environment}", 132 | "manifest_path": f"{ARGOCD_DIR}/{APPS_CHILDREN_DIR}/{environment}", 133 | "repo_url": app_of_apps["parent_app"]["repo_url"], 134 | } 135 | common.process_app_template( 136 | root_app, 137 | common.DEFAULT_NAMESPACE, 138 | common.DESTINATION_CLUSTER_IN_CLUSTER, 139 | app_of_apps["project"]["name"], 140 | ARGOCD_PATH, 141 | environment, 142 | ) 143 | 144 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 145 | 146 | except Exception as e: 147 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 148 | raise e 149 | 150 | 151 | ## ------------------ 152 | 153 | 154 | @task() 155 | def create_namespaces_app_yaml(ctxt): 156 | """ 157 | Create the namespaces-app.yml ArgoCD Application file in the apps-root folder. 158 | 159 | ** This is a helper task and should not be called on its own. 160 | """ 161 | 162 | environment = ctxt["environment"] 163 | task_desc = f"Create namespaces-{environment}-app.yml" 164 | publish(f"START: {task_desc}", LOG_INFO) 165 | 166 | try: 167 | if "argo_proj_yaml" not in ctxt: 168 | raise Exception("Missing app config") 169 | 170 | app_of_apps = copy.deepcopy(ctxt["argo_proj_yaml"]["argocd"]) 171 | parent_app = { 172 | "name": f"namespaces-{app_of_apps['parent_app']['name']}", 173 | "filename": f"namespaces-app-{environment}.yml", 174 | "manifest_path": f"{ARGOCD_ROOT}/namespaces/{environment}", 175 | "repo_url": app_of_apps["parent_app"]["repo_url"], 176 | } 177 | common.process_app_template( 178 | parent_app, 179 | common.DEFAULT_NAMESPACE, 180 | app_of_apps["child_apps"]["destination_cluster"], 181 | app_of_apps["project"]["name"], 182 | os.path.join(APPS_PARENT_PATH, environment), 183 | environment, 184 | ) 185 | 186 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 187 | 188 | except Exception as e: 189 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 190 | raise e 191 | 192 | 193 | ## ------------------ 194 | 195 | 196 | @task() 197 | def create_namespaces_yaml(ctxt): 198 | """ 199 | Create the namespaces.yml file in the namespaces folder. The namespaces are created 200 | based on the namespaces listed in the argo_proj.yml file. 201 | 202 | ** This is a helper task and should not be called on its own. 203 | """ 204 | 205 | environment = ctxt["environment"] 206 | task_desc = f"Create namespaces-{environment}.yml" 207 | publish(f"START: {task_desc}", LOG_INFO) 208 | 209 | try: 210 | if "argo_proj_yaml" not in ctxt: 211 | raise Exception("Missing app config") 212 | 213 | app_of_apps = ctxt["argo_proj_yaml"]["argocd"] 214 | namespaces = [] 215 | for child_app in app_of_apps["child_apps"]["app"]: 216 | namespaces.append(f'{child_app["namespace"]}-{environment}') 217 | 218 | env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), trim_blocks=True) 219 | rendered_data = env.get_template(f"namespaces.yml.j2").stream( 220 | namespaces=namespaces 221 | ) 222 | 223 | rendered_data.dump( 224 | f"{NAMESPACES_PATH}/{environment}/namespaces-{environment}.yml" 225 | ) 226 | 227 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 228 | 229 | except Exception as e: 230 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 231 | raise e 232 | 233 | 234 | ## ------------------ 235 | 236 | 237 | @task() 238 | def create_parent_apps_yaml(ctxt): 239 | """ 240 | Create the {app_name}-app.yml ArgoCD Application file defined parent_app.name in the argo_proj.yml file 241 | 242 | ** This is a helper task and should not be called on its own. 243 | """ 244 | 245 | environment = ctxt["environment"] 246 | task_desc = f"Create {environment} apps-app.yml" 247 | publish(f"START: {task_desc}", LOG_INFO) 248 | 249 | try: 250 | if "argo_proj_yaml" not in ctxt: 251 | raise Exception("Missing app config") 252 | 253 | app_of_apps = copy.deepcopy(ctxt["argo_proj_yaml"]["argocd"]) 254 | parent_app = { 255 | "name": f'{app_of_apps["parent_app"]["name"]}', 256 | "manifest_path": f"{ARGOCD_DIR}/{APPS_CHILDREN_DIR}/{environment}", 257 | "repo_url": app_of_apps["parent_app"]["repo_url"], 258 | } 259 | common.process_app_template( 260 | parent_app, 261 | common.DEFAULT_NAMESPACE, 262 | common.DESTINATION_CLUSTER_IN_CLUSTER, 263 | app_of_apps["project"]["name"], 264 | os.path.join(APPS_PARENT_PATH, environment), 265 | environment, 266 | ) 267 | 268 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 269 | 270 | except Exception as e: 271 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 272 | raise e 273 | 274 | 275 | ## ------------------ 276 | 277 | 278 | @task() 279 | def create_child_apps_yaml(ctxt): 280 | """ 281 | Create the *-app.yml ArgoCD Application files related to the target application, defined in the argo_proj.yml file 282 | These will be created in the apps-{app_name} folder. 283 | 284 | ** This is a helper task and should not be called on its own. 285 | """ 286 | 287 | environment = ctxt["environment"] 288 | task_desc = f"Create child apps for [{environment}] environment" 289 | publish(f"START: {task_desc}", LOG_INFO) 290 | 291 | try: 292 | if "argo_proj_yaml" not in ctxt: 293 | raise Exception("Missing app config") 294 | 295 | app_of_apps = copy.deepcopy(ctxt["argo_proj_yaml"]["argocd"]) 296 | for child_app in app_of_apps["child_apps"]["app"]: 297 | child_app["name"] = f"{child_app['name']}" 298 | child_app["namespace"] = f'{child_app["namespace"]}-{environment}' 299 | common.process_app_template( 300 | child_app, 301 | child_app["namespace"], 302 | app_of_apps["child_apps"]["destination_cluster"], 303 | app_of_apps["project"]["name"], 304 | os.path.join(APPS_CHILDREN_PATH, environment), 305 | environment, 306 | deploy_plugin=child_app.get("deploy_plugin", None), 307 | ) 308 | 309 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 310 | 311 | except Exception as e: 312 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 313 | raise e 314 | 315 | 316 | ## ------------------ 317 | 318 | 319 | @task() 320 | def create_app_of_apps(ctxt): 321 | 322 | for environment in APP_CONFIG["environments"]: 323 | ctxt.config["environment"] = environment 324 | 325 | create_root_app_yaml(ctxt) 326 | # create_namespaces_app_yaml(ctxt) 327 | # create_namespaces_yaml(ctxt) 328 | # create_parent_apps_yaml(ctxt) 329 | create_child_apps_yaml(ctxt) 330 | 331 | ctxt.config["environment"] = "Not Set" 332 | 333 | 334 | ## ------------------ 335 | 336 | 337 | @task( 338 | help={ 339 | "git-username": "Git username (optional for some Git providers)", 340 | "git-token": "Git personal access token", 341 | "git-repo-url": "Git repo HTTPS URL of the repo where the ArgoCD app definitions are located", 342 | "argocd-username": "ArgoCD username. Must be a local ArgoCD account (e.g. admin). Does not work with SSO.", 343 | "argocd-password": "ArgoCD password. Must be a local ArgoCD account. Does not work with SSO.", 344 | }, 345 | pre=[common_actions.cleanup_data_dir], 346 | post=[ 347 | common_actions.argocd_login, 348 | common_actions.clone_repo, 349 | create_folder_structure, 350 | create_project_yaml, 351 | create_app_of_apps, 352 | common_actions.commit_and_push_changes, 353 | ], 354 | ) 355 | def setup_app_of_apps( 356 | ctxt, 357 | git_username=os.environ.get("GIT_USERNAME"), 358 | git_token=os.environ.get("GIT_TOKEN"), 359 | git_repo_url=os.environ.get("GIT_REPO_URL"), 360 | argocd_username=os.environ.get("ARGOCD_USERNAME"), 361 | argocd_password=os.environ.get("ARGOCD_PASSWORD"), 362 | ): 363 | """ 364 | Bootstrap an app in ArgoCD using the "App of Apps" pattern. Arguments can be passed 365 | in through the command line, or they can be set as the following environment variables: 366 | 367 | * GIT_USERNAME 368 | * GIT_TOKEN 369 | * GIT_REPO_URL 370 | * ARGOCD_USERNAME 371 | * ARGOCD_PASSWORD 372 | """ 373 | common.init_bootstrap( 374 | ctxt, git_username, git_token, git_repo_url, argocd_username, argocd_password 375 | ) 376 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/tasks/common/actions.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import os, copy 5 | 6 | from jinja2 import Environment, FileSystemLoader, environment 7 | from invoke import task, exceptions 8 | from pathlib import Path 9 | 10 | from argocd_app_bootstrap.definitions import ( 11 | APP_CONFIG, 12 | ARGO_PROJ_YAML, 13 | DATA_PATH, 14 | PARENT_REPO_PATH, 15 | yaml, 16 | ) 17 | 18 | from argocd_app_bootstrap.utils import common 19 | from argocd_app_bootstrap.utils.common import LOG_ERROR, LOG_INFO, LOG_WARN, publish 20 | 21 | ## ------------------ 22 | 23 | 24 | @task() 25 | def cleanup_data_dir(ctxt): 26 | """ 27 | Delete the contents of the data dir. 28 | 29 | ** This is a helper task and should not be called on its own. 30 | """ 31 | 32 | task_desc = "Clean up data dir" 33 | publish(f"START: {task_desc}", LOG_INFO) 34 | 35 | try: 36 | common.run_command(ctxt, f"rm -rf {DATA_PATH}/*") 37 | 38 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 39 | 40 | except Exception as e: 41 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 42 | raise e 43 | 44 | 45 | ## ------------------ 46 | 47 | 48 | @task() 49 | def argocd_login(ctxt): 50 | """ 51 | Log in to ArgoCD via the argocd CLI. 52 | 53 | ** This is a helper task and should not be called on its own. 54 | """ 55 | 56 | task_desc = "Login to ArgoCD" 57 | publish(f"START: {task_desc}", LOG_INFO) 58 | 59 | try: 60 | insecure = "--insecure" if APP_CONFIG["argocd"]["insecure"] else "" 61 | argocd_host = APP_CONFIG["argocd"]["host"] 62 | argocd_port = APP_CONFIG["argocd"]["port"] 63 | common.run_command( 64 | ctxt, 65 | f"argocd login {argocd_host}:{argocd_port} {insecure} --username {ctxt['argocd_username']} --password {ctxt['argocd_password']}", 66 | ) 67 | 68 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 69 | 70 | except Exception as e: 71 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 72 | raise e 73 | 74 | 75 | ## ------------------ 76 | 77 | 78 | @task() 79 | def clone_repo(ctxt): 80 | """ 81 | Clone the project's git repo to data/repo_tmp. This folder is used to stage the ArgoCD 82 | application and namespace files created by bootstrap_app_of_apps. 83 | 84 | ** This is a helper task and should not be called on its own. 85 | """ 86 | 87 | task_desc = "Initializing git + cloning parent repo" 88 | publish(f"START: {task_desc}", LOG_INFO) 89 | 90 | common.clone_repo(ctxt, ctxt["git_repo_url"], PARENT_REPO_PATH) 91 | 92 | # Use argo_proj.yml from the app repo 93 | argo_proj_yaml_path = os.path.join(PARENT_REPO_PATH, ARGO_PROJ_YAML) 94 | with open(argo_proj_yaml_path, "r") as stream: 95 | argo_proj_yaml_dict = yaml.load(stream) 96 | ctxt.config["argo_proj_yaml"] = common.cleanup_argo_proj_yaml( 97 | argo_proj_yaml_dict 98 | ) 99 | 100 | # Make sure that argo_proj.yml has the correct repo reference 101 | with open(argo_proj_yaml_path, "w") as argo_proj_file: 102 | yaml.dump(ctxt["argo_proj_yaml"].__dict__["_config"], argo_proj_file) 103 | 104 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 105 | 106 | 107 | ## ------------------ 108 | 109 | 110 | @task() 111 | def commit_and_push_changes(ctxt): 112 | """ 113 | Commit and push the newly-created files to git. 114 | 115 | ** This is a helper task and should not be called on its own. 116 | """ 117 | 118 | task_desc = "Commit and push changes" 119 | publish(f"START: {task_desc}", LOG_INFO) 120 | target_repo_path = ctxt["git_repo_path"] 121 | 122 | try: 123 | 124 | common.run_command(ctxt, f"cd {target_repo_path} && git status") 125 | common.run_command(ctxt, f"cd {target_repo_path} && git add .") 126 | common.run_command( 127 | ctxt, 128 | f"cd {target_repo_path} && git commit -m 'ArgoCD app configs'", 129 | raise_exception_on_err=False, 130 | ) 131 | common.run_command( 132 | ctxt, f"cd {target_repo_path} && git push", raise_exception_on_err=False 133 | ) 134 | 135 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 136 | 137 | except Exception as e: 138 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 139 | raise e 140 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/tasks/deploy/setup/actions.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | import os, copy, shutil 5 | 6 | from jinja2 import Environment, FileSystemLoader, environment 7 | from invoke import task, exceptions 8 | from pathlib import Path 9 | 10 | from argocd_app_bootstrap.definitions import ( 11 | APP_CONFIG, 12 | CHILD_REPOS_PATH, 13 | HELM_BASE_PATH, 14 | HELM_TEMPLATES_PATH, 15 | KUSTOMIZED_HELM_PATH, 16 | OVERLAYS_PATH, 17 | PATCH_DIR, 18 | DEPLOY_TEMPLATES_PATH, 19 | yaml, 20 | ) 21 | 22 | import argocd_app_bootstrap.tasks.common.actions as common_actions 23 | 24 | from argocd_app_bootstrap.utils import common 25 | from argocd_app_bootstrap.utils.common import LOG_ERROR, LOG_INFO, LOG_WARN, publish 26 | 27 | ## ------------------ 28 | 29 | 30 | @task() 31 | def clone_child_repo(ctxt): 32 | """ 33 | Clone the project's git repo to data/repo_tmp. This folder is used to stage the ArgoCD 34 | application and namespace files created by bootstrap_app_of_apps. 35 | 36 | ** This is a helper task and should not be called on its own. 37 | """ 38 | 39 | git_repo = ctxt["child_git_repo"] 40 | task_desc = "Initializing git + cloning child repo" 41 | publish(f"START: {task_desc}", LOG_INFO) 42 | 43 | common.clone_repo(ctxt, git_repo, CHILD_REPOS_PATH) 44 | 45 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 46 | 47 | 48 | ## ------------------ 49 | 50 | 51 | @task() 52 | def create_folder_structure(ctxt): 53 | """ 54 | Create the folder structure for a Kustomized Helm app. 55 | 56 | ** This is a helper task and should not be called on its own. 57 | """ 58 | 59 | task_desc = "Create kustomized helm folder structure" 60 | publish(f"START: {task_desc}", LOG_INFO) 61 | 62 | try: 63 | if "argo_proj_yaml" not in ctxt: 64 | raise Exception("Missing app config") 65 | 66 | Path(KUSTOMIZED_HELM_PATH).mkdir(parents=True, exist_ok=True) 67 | Path(HELM_BASE_PATH).mkdir(parents=True, exist_ok=True) 68 | Path(HELM_TEMPLATES_PATH).mkdir(parents=True, exist_ok=True) 69 | Path(OVERLAYS_PATH).mkdir(parents=True, exist_ok=True) 70 | 71 | for environment in APP_CONFIG["environments"]: 72 | Path(os.path.join(OVERLAYS_PATH, environment, PATCH_DIR)).mkdir( 73 | parents=True, exist_ok=True 74 | ) 75 | 76 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 77 | 78 | except Exception as e: 79 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 80 | raise e 81 | 82 | 83 | ## ------------------ 84 | 85 | 86 | @task() 87 | def create_template_files(ctxt): 88 | """ 89 | Create template files for a Kustomized Helm app. 90 | 91 | ** This is a helper task and should not be called on its own. 92 | """ 93 | 94 | task_desc = "Create app of apps folder structure" 95 | publish(f"START: {task_desc}", LOG_INFO) 96 | 97 | try: 98 | if "argo_proj_yaml" not in ctxt: 99 | raise Exception("Missing app config") 100 | 101 | for environment in APP_CONFIG["environments"]: 102 | shutil.copy2( 103 | f"{DEPLOY_TEMPLATES_PATH}/deployment_patch.yml.j2", 104 | f"{OVERLAYS_PATH}/{environment}/{PATCH_DIR}/deployment_patch.yml", 105 | ) 106 | 107 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 108 | 109 | except Exception as e: 110 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 111 | raise e 112 | 113 | 114 | ## ------------------ 115 | 116 | 117 | @task() 118 | def render_helm_base_yamls(ctxt): 119 | """ 120 | Render helm_base folder's Helm templates and kustomization.yml. 121 | 122 | ** This is a helper task and should not be called on its own. 123 | """ 124 | 125 | task_desc = "Create Helm Chart.yaml and deployment YAML templates" 126 | publish(f"START: {task_desc}", LOG_INFO) 127 | 128 | try: 129 | if "argo_proj_yaml" not in ctxt: 130 | raise Exception("Missing app config") 131 | 132 | env = Environment( 133 | loader=FileSystemLoader(DEPLOY_TEMPLATES_PATH), trim_blocks=True 134 | ) 135 | 136 | # Render Chart.yaml 137 | rendered_data = env.get_template(f"Chart.yaml.j2").stream( 138 | app_name=ctxt["child_app_name"], 139 | app_version=ctxt["argo_proj_yaml"]["argocd"]["parent_app"]["version"], 140 | ) 141 | rendered_data.dump(f"{HELM_BASE_PATH}/Chart.yaml") 142 | 143 | # Render deployment.yml 144 | rendered_data = env.get_template(f"deployment.yml.j2").stream() 145 | rendered_data.dump(f"{HELM_TEMPLATES_PATH}/deployment.yml") 146 | 147 | # Render service.yml 148 | rendered_data = env.get_template(f"service.yml.j2").stream() 149 | rendered_data.dump(f"{HELM_TEMPLATES_PATH}/service.yml") 150 | 151 | # Render mapping.yml 152 | rendered_data = env.get_template(f"mapping.yml.j2").stream( 153 | app_name=ctxt["child_app_name"] 154 | ) 155 | rendered_data.dump(f"{HELM_TEMPLATES_PATH}/mapping.yml") 156 | 157 | # Render kustomization_base.yml 158 | rendered_data = env.get_template(f"kustomization_base.yml.j2").stream( 159 | app_name=ctxt["child_app_name"], 160 | parent_app=ctxt["argo_proj_yaml"]["argocd"]["parent_app"]["name"], 161 | app_version=ctxt["argo_proj_yaml"]["argocd"]["parent_app"]["version"], 162 | ) 163 | rendered_data.dump(f"{HELM_BASE_PATH}/kustomization.yml") 164 | 165 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 166 | 167 | except Exception as e: 168 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 169 | raise e 170 | 171 | 172 | ## ------------------ 173 | 174 | 175 | @task() 176 | def render_overlay_templates_yaml(ctxt): 177 | """ 178 | Render YAML files in the overlay folders. 179 | 180 | ** This is a helper task and should not be called on its own. 181 | """ 182 | 183 | task_desc = "Create namespace.yaml" 184 | publish(f"START: {task_desc}", LOG_INFO) 185 | 186 | try: 187 | if "argo_proj_yaml" not in ctxt: 188 | raise Exception("Missing app config") 189 | 190 | env = Environment( 191 | loader=FileSystemLoader(DEPLOY_TEMPLATES_PATH), trim_blocks=True 192 | ) 193 | 194 | for environment in APP_CONFIG["environments"]: 195 | # Render overlay folder's namespace.yml 196 | rendered_data = env.get_template(f"namespace.yml.j2").stream( 197 | namespace=f'{ctxt["child_namespace"]}-{environment}' 198 | ) 199 | rendered_data.dump(f"{OVERLAYS_PATH}/{environment}/namespace.yml") 200 | 201 | # Render overlay folder's kustomization.yml 202 | rendered_data = env.get_template(f"kustomization_overlays.yml.j2").stream( 203 | namespace=f'{ctxt["child_namespace"]}-{environment}' 204 | ) 205 | rendered_data.dump(f"{OVERLAYS_PATH}/{environment}/kustomization.yml") 206 | 207 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 208 | 209 | except Exception as e: 210 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 211 | raise e 212 | 213 | 214 | ## ------------------ 215 | 216 | 217 | @task() 218 | def scaffold_k8s_deployment(ctxt): 219 | """ 220 | Create scaffolding folder structure for standardized k8s deployments 221 | 222 | ** This is a helper task and should not be called on its own. 223 | """ 224 | 225 | task_desc = "Scaffold" 226 | publish(f"START: {task_desc}", LOG_INFO) 227 | 228 | try: 229 | apps_list = ctxt["argo_proj_yaml"]["argocd"]["child_apps"]["app"] 230 | for app in apps_list: 231 | common.run_command(ctxt, f"rm -rf {CHILD_REPOS_PATH}") 232 | ctxt["child_git_repo"] = app["repo_url"] 233 | ctxt["child_app_name"] = app["name"] 234 | ctxt["child_namespace"] = app["namespace"] 235 | publish(f"INFO: Now processing app {ctxt['child_app_name']}", LOG_INFO) 236 | 237 | clone_child_repo(ctxt) 238 | create_folder_structure(ctxt) 239 | create_template_files(ctxt) 240 | render_helm_base_yamls(ctxt) 241 | render_overlay_templates_yaml(ctxt) 242 | common_actions.commit_and_push_changes(ctxt), 243 | 244 | publish(f"SUCCESS: {task_desc}", LOG_INFO) 245 | 246 | except Exception as e: 247 | publish(f"FAIL: {task_desc}. CAUSE: {str(e)}", LOG_ERROR) 248 | raise e 249 | 250 | 251 | ## ------------------ 252 | 253 | 254 | @task( 255 | help={ 256 | "git-username": "Git username (optional for some Git providers)", 257 | "git-token": "Git personal access token", 258 | "git-repo-url": "Git repo HTTPS URL of the repo where the ArgoCD app definitions are located", 259 | "argocd-username": "ArgoCD username. Must be a local ArgoCD account (e.g. admin). Does not work with SSO.", 260 | "argocd-password": "ArgoCD password. Must be a local ArgoCD account. Does not work with SSO.", 261 | }, 262 | pre=[common_actions.cleanup_data_dir], 263 | post=[common_actions.clone_repo, scaffold_k8s_deployment], 264 | ) 265 | def bootstrap_k8s_deployment( 266 | ctxt, 267 | git_username=os.environ.get("GIT_USERNAME"), 268 | git_token=os.environ.get("GIT_TOKEN"), 269 | git_repo_url=os.environ.get("GIT_REPO_URL"), 270 | argocd_username=os.environ.get("ARGOCD_USERNAME"), 271 | argocd_password=os.environ.get("ARGOCD_PASSWORD"), 272 | ): 273 | """ 274 | Bootstrap an app in ArgoCD using the "App of Apps" pattern. Arguments can be passed 275 | in through the command line, or they can be set as the following environment variables: 276 | 277 | * GIT_USERNAME 278 | * GIT_TOKEN 279 | * GIT_REPO_URL 280 | * ARGOCD_USERNAME 281 | * ARGOCD_PASSWORD 282 | """ 283 | common.init_bootstrap( 284 | ctxt, 285 | git_username, 286 | git_token, 287 | git_repo_url, 288 | argocd_username, 289 | argocd_password, 290 | target_repo_path=CHILD_REPOS_PATH, 291 | ) 292 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/application.yml.j2: -------------------------------------------------------------------------------- 1 | apiVersion: argoproj.io/v1alpha1 2 | kind: Application 3 | metadata: 4 | name: {{ app['name'] }} 5 | namespace: argocd 6 | finalizers: 7 | - resources-finalizer.argocd.argoproj.io 8 | spec: 9 | destination: 10 | namespace: {{ namespace }} 11 | name: {{ destination_cluster }} 12 | project: {{ project_name }} 13 | source: 14 | path: {{ app['manifest_path'] }} 15 | repoURL: {{ app['repo_url'] }} 16 | targetRevision: HEAD 17 | {% if deploy_plugin is defined and deploy_plugin == 'kustomized-helm' %} 18 | plugin: 19 | name: kustomized-helm 20 | {% endif %} 21 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/Chart.yaml.j2: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | description: A Helm chart for Kubernetes 3 | name: {{ app_name }} 4 | version: 0.1.0 5 | appVersion: {{ app_version }} -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/deployment.yml.j2: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 3 | kind: Deployment 4 | metadata: 5 | name: deployment 6 | spec: 7 | replicas: 0 8 | selector: 9 | matchLabels: 10 | app: {{ '{{ .Release.Name }}' }} 11 | template: 12 | metadata: 13 | labels: 14 | app: {{ '{{ .Release.Name }}' }} 15 | spec: 16 | containers: 17 | - name: {{ '{{ .Release.Name }}' }} 18 | image: blah 19 | imagePullPolicy: Always 20 | ports: 21 | - containerPort: 80 22 | resources: 23 | requests: 24 | cpu: "0.1" 25 | memory: "500m" 26 | limits: 27 | cpu: "0.1" 28 | memory: 100Mi 29 | livenessProbe: 30 | httpGet: 31 | path: / 32 | port: 80 33 | initDelaySeconds: 20 34 | periodSeconds: 20 35 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/deployment_patch.yml.j2: -------------------------------------------------------------------------------- 1 | - op: replace 2 | path: /spec/replicas 3 | value: 1 4 | - op: replace 5 | path: /spec/template/spec/containers/0/livenessProbe/periodSeconds 6 | value: 120 -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/kustomization_base.yml.j2: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | commonLabels: 5 | app.kubernetes.io/name: {{ app_name }} 6 | app.kubernetes.io/version: {{ app_version }} 7 | app.kubernetes.io/part-of: {{ parent_app }} 8 | app.kubernetes.io/managed-by: argocd 9 | 10 | resources: 11 | - all.yml -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/kustomization_overlays.yml.j2: -------------------------------------------------------------------------------- 1 | apiVersion: kustomize.config.k8s.io/v1beta1 2 | kind: Kustomization 3 | 4 | bases: 5 | - ../../helm_base 6 | 7 | namespace: {{ namespace }} 8 | 9 | resources: 10 | - namespace.yml 11 | 12 | images: 13 | - name: .azurecr.io/: 14 | newName: 15 | newTag: 16 | 17 | patchesJson6902: 18 | - target: 19 | group: apps 20 | version: v1 21 | kind: Deployment 22 | name: deployment 23 | path: patch/deployment_patch.yml 24 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/mapping.yml.j2: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: getambassador.io/v2 3 | kind: Mapping 4 | metadata: 5 | name: mapping 6 | spec: 7 | prefix: /{{ app_name }}/ 8 | service: service:80 -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/namespace.yml.j2: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Namespace 4 | metadata: 5 | name: {{ namespace }} 6 | annotations: 7 | argocd.argoproj.io/sync-wave: "-1" 8 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/deploy/service.yml.j2: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Service 4 | metadata: 5 | name: service 6 | spec: 7 | ports: 8 | - protocol: TCP 9 | port: 80 10 | targetPort: 80 11 | type: ClusterIP 12 | selector: 13 | app: {{ '{{ .Release.Name }}' }} -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/namespaces.yml.j2: -------------------------------------------------------------------------------- 1 | {% for namespace in namespaces %} 2 | --- 3 | apiVersion: v1 4 | kind: Namespace 5 | metadata: 6 | name: {{ namespace }} 7 | annotations: 8 | argocd.argoproj.io/sync-wave: "-1" 9 | 10 | {% endfor %} -------------------------------------------------------------------------------- /argocd_app_bootstrap/templates/project.yml.j2: -------------------------------------------------------------------------------- 1 | apiVersion: argoproj.io/v1alpha1 2 | kind: AppProject 3 | metadata: 4 | name: {{ project_name }} 5 | namespace: argocd 6 | # Finalizer that ensures that project is not deleted until it is not referenced by any application 7 | finalizers: 8 | - resources-finalizer.argocd.argoproj.io 9 | spec: 10 | # Project description 11 | description: {{ project_description }} 12 | 13 | # Allow manifests to deploy from any Git repos 14 | sourceRepos: 15 | - '*' 16 | 17 | # Only permit applications to deploy to the guestbook namespace in the same cluster 18 | destinations: 19 | - namespace: '*' 20 | server: '*' 21 | 22 | # Deny all cluster-scoped resources from being created, except for Namespace 23 | clusterResourceWhitelist: 24 | - group: '*' 25 | kind: '*' 26 | -------------------------------------------------------------------------------- /argocd_app_bootstrap/utils/common.py: -------------------------------------------------------------------------------- 1 | import os, inspect, re, string 2 | 3 | from invoke import Context 4 | from jinja2 import Environment, FileSystemLoader 5 | from structlog import get_logger 6 | 7 | 8 | from argocd_app_bootstrap.definitions import ( 9 | APP_CONFIG, 10 | ARGO_PROJ_YAML, 11 | PARENT_REPO_PATH, 12 | TEMPLATES_PATH, 13 | yaml, 14 | ) 15 | 16 | ## ------------------ 17 | 18 | 19 | def str2bool(value: str): 20 | """ 21 | Converts a string to a python bool 22 | 23 | Args: 24 | value (str): Value to convert 25 | 26 | Returns: 27 | [type]: [description] 28 | """ 29 | if type(value) == bool: 30 | return_val = value 31 | else: 32 | return_val = value.lower() in ("yes", "true", "t", "1") 33 | 34 | return return_val 35 | 36 | 37 | ## ------------------ 38 | 39 | logger = get_logger() 40 | 41 | # Logging states 42 | LOG_INFO = "INFO" 43 | LOG_WARN = "WARN" 44 | LOG_ERROR = "ERROR" 45 | 46 | DEFAULT_NAMESPACE = "default" 47 | DESTINATION_CLUSTER_IN_CLUSTER = "in-cluster" 48 | 49 | ## ------------------ 50 | 51 | 52 | def run_command(ctxt: Context, command: str, raise_exception_on_err=True, hide=None): 53 | """ 54 | Run command-line command 55 | 56 | Args: 57 | ctxt (Context): PyInvoke Context. http://docs.pyinvoke.org/en/stable/api/context.html 58 | command (str): The command to execute 59 | raise_exception_on_err (bool, optional): If false, don't raise an exception. We can use this to capture the error message. Defaults to True. 60 | hide (bool, optional): If true, hide the command outputs. Valid values: "err", "out", "both", "none". Defaults to None. 61 | 62 | Raises: 63 | Exception: Exception raised if command errs out (non-zero return code). 64 | 65 | Returns: 66 | Result: PyInvoke result object. http://docs.pyinvoke.org/en/stable/api/runners.html 67 | """ 68 | 69 | result = ctxt.run(command, warn=True, hide=hide) 70 | 71 | if raise_exception_on_err and (result.exited != 0): 72 | raise Exception(f"{result.stderr}") 73 | 74 | return result 75 | 76 | 77 | ## ------------------ 78 | 79 | 80 | def publish(msg: str, type: str): 81 | """ 82 | Wrapper for logging. Future state: post message to listener endpoint (future state) 83 | 84 | Args: 85 | msg (str): The message to be published. 86 | type (str): The log type. Valid values: LOG_ERROR, LOG_INFO, LOG_WARN 87 | """ 88 | 89 | # Always include these in every log 90 | log = logger.bind( 91 | app="argocd_app_bootstrap", caller=inspect.currentframe().f_back.f_code.co_name 92 | ) 93 | 94 | # Loggers for different occasions 95 | if type.upper() == LOG_INFO: 96 | log.info(msg) 97 | 98 | if type.upper() == LOG_ERROR: 99 | log.error(f"AN ERROR HAS OCCURRED: {msg}") 100 | 101 | if type.upper() == LOG_WARN: 102 | log.warning(msg) 103 | 104 | 105 | ## ------------------ 106 | 107 | 108 | def cleanup_str_for_k8s(value: str): 109 | """ 110 | Clean up string so that it is kubernetes-compatible: remove special chars (except "-"), and 111 | convert all text to lower-case. 112 | 113 | Args: 114 | value (str): The string to clean up 115 | 116 | Returns: 117 | str: The kubernetes-compatible string 118 | """ 119 | 120 | value = value.replace("_", "-") 121 | invalid_chars = string.punctuation.replace("-", "") + string.whitespace 122 | chars = re.escape(invalid_chars) 123 | new_value = re.sub(r"[" + chars + "]", "", value).lower() 124 | return new_value 125 | 126 | 127 | ## ------------------ 128 | 129 | 130 | def cleanup_argo_proj_yaml(argo_proj_yaml): 131 | 132 | argo_proj_yaml["argocd"]["project"]["name"] = cleanup_str_for_k8s( 133 | argo_proj_yaml["argocd"]["project"]["name"] 134 | ) 135 | 136 | argo_proj_yaml["argocd"]["parent_app"]["name"] = cleanup_str_for_k8s( 137 | argo_proj_yaml["argocd"]["parent_app"]["name"] 138 | ) 139 | 140 | for child_app in argo_proj_yaml["argocd"]["child_apps"]["app"]: 141 | child_app["name"] = cleanup_str_for_k8s(child_app["name"]) 142 | child_app["namespace"] = cleanup_str_for_k8s(child_app["namespace"]) 143 | 144 | return argo_proj_yaml 145 | 146 | 147 | ## ------------------ 148 | 149 | 150 | def init_bootstrap( 151 | ctxt: Context, 152 | git_username: str, 153 | git_token: str, 154 | git_repo_url: str, 155 | argocd_username: str, 156 | argocd_password: str, 157 | target_repo_path=PARENT_REPO_PATH, 158 | target_environment=None, 159 | ): 160 | """ 161 | Set up context variables. 162 | 163 | Args: 164 | ctxt (Context): PyInvoke Context. http://docs.pyinvoke.org/en/stable/api/context.html 165 | git_username (str): Git username (not required by some git providers) 166 | git_token (str): Git personal access token 167 | git_repo_url (str): Git repo HTTPS URL of the repo where the ArgoCD app definitions are located 168 | argocd_username (str): ArgoCD username 169 | argocd_password (str): ArgoCD password 170 | target_environment (str): Target environment to deploy to 171 | 172 | Raises: 173 | Exception: Raise exception when any of the params (except git username) is missing. 174 | """ 175 | 176 | if ( 177 | (git_token is None) 178 | or (git_repo_url is None) 179 | or (argocd_username is None) 180 | or (argocd_password is None) 181 | ): 182 | msg = "ERROR: Missing arg(s). Mandatory args: git-token, git-repo-url, argocd-username, argocd-password" 183 | publish(msg, LOG_ERROR) 184 | raise Exception(msg) 185 | 186 | # Git details 187 | ctxt.config["git_username"] = ( 188 | git_username if (git_username is not None) and (git_username != "") else None 189 | ) 190 | ctxt.config["git_token"] = git_token 191 | ctxt.config["git_repo_url"] = git_repo_url 192 | 193 | # ArgoCD server credentials 194 | ctxt.config["argocd_username"] = argocd_username 195 | ctxt.config["argocd_password"] = argocd_password 196 | 197 | ctxt.config["git_repo_path"] = target_repo_path 198 | 199 | # Target environment 200 | if target_environment is not None: 201 | ctxt.config["target_environment"] = target_environment.lower() 202 | 203 | 204 | ## ------------------ 205 | 206 | 207 | def process_app_template( 208 | app_details: dict, 209 | namespace: str, 210 | destination_cluster: str, 211 | project_name: str, 212 | destination_dir: str, 213 | environment: str, 214 | deploy_plugin=None, 215 | ): 216 | """ 217 | Apply the ArgoCD application template to the given data set. 218 | 219 | Args: 220 | app_details (dict): Information about the app 221 | namespace (str): App's target namespace 222 | destination_cluster (str): App target ArgoCD cluster 223 | project_name (str): Name of ArgoCD project that the app belongs to 224 | destination_dir (str): Destination directory that transformed YAML file is written to. 225 | environment (str): Target environment (e.g. dev, qa, prod) 226 | deploy_plugin (str): Plugin to use for deployment (other than Helm or Kustomize) 227 | """ 228 | 229 | env = Environment(loader=FileSystemLoader(TEMPLATES_PATH), trim_blocks=True) 230 | 231 | app_details["name"] = f"{app_details['name']}-app-{environment}" 232 | 233 | # app_details["name"] = app_details["name"] 234 | rendered_data = env.get_template(f"application.yml.j2").stream( 235 | app=app_details, 236 | namespace=namespace, 237 | destination_cluster=destination_cluster, 238 | project_name=f"{project_name}-{environment}", 239 | deploy_plugin=deploy_plugin, 240 | ) 241 | 242 | filename = app_details.get("filename", f"{app_details['name']}.yml") 243 | rendered_data.dump(f"{destination_dir}/{filename}") 244 | publish(f"INFO: Created [{destination_dir}/{filename}]", LOG_INFO) 245 | 246 | 247 | ## ------------------ 248 | 249 | 250 | def get_repos(ctxt, children_only=False): 251 | 252 | # Get child repos 253 | repos_list = [ 254 | child_app["repo_url"] 255 | for child_app in ctxt["argo_proj_yaml"]["argocd"]["child_apps"]["app"] 256 | ] 257 | 258 | # Add parent repo 259 | if not children_only: 260 | repos_list.append(ctxt["argo_proj_yaml"]["argocd"]["parent_app"]["repo_url"]) 261 | 262 | # Remove duplicates from list 263 | repos_list = list(dict.fromkeys(repos_list)) 264 | 265 | return repos_list 266 | 267 | 268 | ## ------------------ 269 | 270 | 271 | def clone_repo(ctxt, git_repo, target_path): 272 | 273 | git_provider = APP_CONFIG["git-provider"] 274 | git_url_prefix = f"git@{git_provider}:" 275 | if os.environ["ENV"] != "development": 276 | 277 | git_url_prefix = f"https://{git_provider}/" 278 | os.environ["MY_GIT_TOKEN"] = ctxt["git_token"] 279 | 280 | run_command( 281 | ctxt, 282 | f'git config --global url."https://$MY_GIT_TOKEN@{git_provider}/".insteadOf "https://{git_provider}/"', 283 | ) 284 | publish("INFO: Set up token access for git", LOG_INFO) 285 | 286 | run_command(ctxt, 'git config --global user.name "ArgoCD Admin"') 287 | run_command( 288 | ctxt, f'git config --global user.email {APP_CONFIG["argocd-admin-email"]}' 289 | ) 290 | 291 | git_url = git_repo.replace(f"https://{git_provider}/", git_url_prefix) 292 | publish(f"INFO: Using Git URL [{git_url}]", LOG_INFO) 293 | run_command(ctxt, f"git clone {git_url} {target_path}") 294 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | package_name="argocd_app_bootstrap" 4 | app_name="argocd-app-bootstrap" 5 | 6 | version=$(cat ${package_name}/_version.py | grep __version__ | cut -d '=' -f2 | tr -d "\"" | tr -d " ") 7 | 8 | # Cleanup 9 | rm -rf build 10 | rm -rf dist 11 | rm -rf ${package_name}.egg-info 12 | rm -rf venv/lib/python3.8/site-packages/argocd_app_bootstrap 13 | rm -rf venv/lib/python3.8/site-packages/argocd_app_bootstrap-${version}.dist-info 14 | find . -type d -name __pycache__ -not -path "./venv/*" -exec rm -rf {} \; 15 | pip uninstall -y ${app_name} 16 | 17 | # Build package 18 | python setup.py bdist_wheel 19 | 20 | # Install package 21 | pip install dist/${package_name}-${version}-py3-none-any.whl 22 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | # We need a base image running python3.7 since our slim ubuntu phusion image installed 3.6 by default and it was voodoo to try to get 3.7 2 | FROM python:3.8.5-slim-buster 3 | 4 | RUN apt-get update && apt-get -y install \ 5 | gcc \ 6 | apt-transport-https \ 7 | curl \ 8 | gnupg2 \ 9 | wget \ 10 | git-all 11 | 12 | # Install kubectl 13 | RUN curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add - 14 | RUN echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | tee -a /etc/apt/sources.list.d/kubernetes.list 15 | RUN apt-get update && apt-get install -y kubectl 16 | 17 | # Install gcloud & additional components 18 | RUN curl -sSL https://sdk.cloud.google.com > /tmp/gcl && bash /tmp/gcl --install-dir=/usr/local/bin/gcloud --disable-prompts 19 | ENV PATH=$PATH:/usr/local/bin/gcloud/google-cloud-sdk/bin 20 | RUN gcloud components update -q && \ 21 | gcloud components install alpha -q && \ 22 | gcloud components install beta -q 23 | 24 | # Set up working directory 25 | ENV WORKDIR="/workdir" 26 | RUN mkdir -p ${WORKDIR} 27 | WORKDIR ${WORKDIR} 28 | 29 | # Python package 30 | ARG ARGOCD_APP_BOOTSTRAP 31 | COPY "argocd_app_bootstrap-${ARGOCD_APP_BOOTSTRAP}-py3-none-any.whl" . 32 | 33 | # Install Python dependencies 34 | COPY requirements.txt . 35 | RUN pip install --upgrade pip \ 36 | && pip install -r requirements.txt 37 | 38 | RUN pip install "argocd_app_bootstrap-${ARGOCD_APP_BOOTSTRAP}-py3-none-any.whl" 39 | 40 | # Install ArgoCD CLI 41 | COPY argocd-linux-amd64 /usr/local/bin/argocd 42 | RUN chmod +x /usr/local/bin/argocd 43 | 44 | # gcloud credentials 45 | COPY gcloud-sa.json . 46 | 47 | COPY startup.sh . 48 | RUN chmod 755 startup.sh 49 | 50 | # CMD ["/workdir/startup.sh"] 51 | CMD ["/bin/bash"] -------------------------------------------------------------------------------- /docker/argocd-linux-amd64: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:3f169184a790338eb03bca9d0986981025a35b3380c7160afa5bda9191ce10dc 3 | size 72274461 4 | -------------------------------------------------------------------------------- /docker/docker_build.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | # Note: Run this script from the repo root 4 | # Sample usage: ./docker/docker_build.sh 5 | 6 | docker_tag=$1 7 | 8 | # Get latest versions of our packages 9 | argocd_app_bootstrap_version=$(cat argocd_app_bootstrap/_version.py | grep __version__ | cut -d '=' -f2 | tr -d "\"" | tr -d " ") 10 | 11 | echo "argocd_app_bootstrap version: " $argocd_app_bootstrap_version 12 | 13 | # Build python code 14 | ./build.sh 15 | 16 | # Copy wheel files for d0 dependencies 17 | rm docker/*.whl 18 | cp dist/argocd_app_bootstrap-${argocd_app_bootstrap_version}-py3-none-any.whl docker/. 19 | 20 | # Copy requirements.txt for external Python dependencies 21 | rm docker/requirements*.txt 22 | cp requirements.txt docker/. 23 | 24 | # Copy gcloud credentials file 25 | rm docker/gcloud-sa.json 26 | cp /.json docker/gcloud-sa.json 27 | 28 | # Build image 29 | docker build --build-arg ARGOCD_APP_BOOTSTRAP=${argocd_app_bootstrap_version} docker -t argocdapp-bootstrap:${docker_tag} 30 | 31 | -------------------------------------------------------------------------------- /docker/startup.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | 3 | gcloud auth activate-service-account --key-file= 4 | gcloud config set project 5 | gcloud container clusters get-credentials --region= 6 | 7 | -------------------------------------------------------------------------------- /img/app_bundle_repo_structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/d0-labs/argocd-app-bootstrap/8c93133dd8410bdb75134b8f874d4c9820e12f0d/img/app_bundle_repo_structure.png -------------------------------------------------------------------------------- /img/child_repo_kustomized_helm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/d0-labs/argocd-app-bootstrap/8c93133dd8410bdb75134b8f874d4c9820e12f0d/img/child_repo_kustomized_helm.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | ruamel.yaml==0.16.10 2 | invoke==1.4.1 3 | pre-commit==2.4.0 4 | black==19.10b0 5 | jinja2==2.11.2 6 | structlog==20.1.0 7 | colorama==0.4.4 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | _locals = {} 4 | with open("argocd_app_bootstrap/_version.py") as fp: 5 | exec(fp.read(), None, _locals) 6 | version = _locals["__version__"] 7 | 8 | setup( 9 | name="argocd_app_bootstrap", 10 | version=version, 11 | url="https://github.com/d0-labs/argocd-app-bootstrap", 12 | author="Adriana Villela", 13 | author_email="adriana@dzerolabs.io", 14 | install_requires=["invoke"], 15 | packages=find_packages(exclude=["tests"]), 16 | include_package_data=True, 17 | python_requires=">=3.8", 18 | entry_points={ 19 | "console_scripts": ["argo-bootstrap = argocd_app_bootstrap.main:program.run"] 20 | }, 21 | ) 22 | --------------------------------------------------------------------------------