├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── ci.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── example ├── README.md ├── composition.yaml ├── functions.yaml └── xr.yaml ├── function ├── __version__.py ├── fn.py └── main.py ├── package ├── crossplane.yaml └── input │ └── template.fn.crossplane.io_inputs.yaml ├── pyproject.toml ├── renovate.json └── tests └── test_fn.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Help us diagnose and fix bugs in this Function 4 | labels: bug 5 | --- 6 | 13 | 14 | ### What happened? 15 | 19 | 20 | 21 | ### How can we reproduce it? 22 | 27 | 28 | ### What environment did it happen in? 29 | Function version: 30 | 31 | 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Help us make this Function more useful 4 | labels: enhancement 5 | --- 6 | 13 | 14 | ### What problem are you facing? 15 | 20 | 21 | ### How could this Function help solve your problem? 22 | 25 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | ### Description of your changes 10 | 11 | 21 | 22 | Fixes # 23 | 24 | I have: 25 | 26 | - [ ] Read and followed Crossplane's [contribution process]. 27 | - [ ] Added or updated unit tests for my change. 28 | 29 | [contribution process]: https://git.io/fj2m9 30 | [docs]: https://docs.crossplane.io/contribute/contribute 31 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - release-* 8 | pull_request: {} 9 | workflow_dispatch: 10 | inputs: 11 | version: 12 | description: Package version (e.g. v0.1.0) 13 | required: false 14 | 15 | env: 16 | # Common versions 17 | PYTHON_VERSION: '3.11' 18 | HATCH_VERSION: '1.12.0' 19 | DOCKER_BUILDX_VERSION: 'v0.24.0' 20 | 21 | # These environment variables are important to the Crossplane CLI install.sh 22 | # script. They determine what version it installs. 23 | XP_CHANNEL: stable 24 | XP_VERSION: v1.20.0 25 | 26 | # The package to push, without a version tag. The default matches GitHub. For 27 | # example xpkg.crossplane.io/crossplane/function-template-go. Note that 28 | # xpkg.crossplane.io is just an alias for ghcr.io, so we upload to ghcr.io but 29 | # this'll be pulled from xpkg.crossplane.io. 30 | XPKG: ghcr.io/${{ github.repository}} 31 | 32 | # The package version to push. The default is 0.0.0-gitsha. 33 | XPKG_VERSION: ${{ inputs.version }} 34 | 35 | jobs: 36 | lint: 37 | runs-on: ubuntu-24.04 38 | steps: 39 | - name: Checkout 40 | uses: actions/checkout@v4 41 | 42 | - name: Setup Python 43 | uses: actions/setup-python@v5 44 | with: 45 | python-version: ${{ env.PYTHON_VERSION }} 46 | 47 | - name: Setup Hatch 48 | run: pipx install hatch==${{ env.HATCH_VERSION }} 49 | 50 | - name: Lint 51 | run: hatch fmt 52 | 53 | unit-test: 54 | runs-on: ubuntu-24.04 55 | steps: 56 | - name: Checkout 57 | uses: actions/checkout@v4 58 | 59 | - name: Setup Python 60 | uses: actions/setup-python@v5 61 | with: 62 | python-version: ${{ env.PYTHON_VERSION }} 63 | 64 | - name: Setup Hatch 65 | run: pipx install hatch==${{ env.HATCH_VERSION }} 66 | 67 | - name: Run Unit Tests 68 | run: hatch test --all --randomize 69 | 70 | # We want to build most packages for the amd64 and arm64 architectures. To 71 | # speed this up we build single-platform packages in parallel. We then upload 72 | # those packages to GitHub as a build artifact. The push job downloads those 73 | # artifacts and pushes them as a single multi-platform package. 74 | build: 75 | runs-on: ubuntu-24.04 76 | strategy: 77 | fail-fast: true 78 | matrix: 79 | arch: 80 | - amd64 81 | - arm64 82 | steps: 83 | - name: Setup QEMU 84 | uses: docker/setup-qemu-action@v3 85 | with: 86 | platforms: all 87 | 88 | - name: Setup Docker Buildx 89 | uses: docker/setup-buildx-action@v3 90 | with: 91 | version: ${{ env.DOCKER_BUILDX_VERSION }} 92 | install: true 93 | 94 | - name: Checkout 95 | uses: actions/checkout@v4 96 | 97 | # We ask Docker to use GitHub Action's native caching support to speed up 98 | # the build, per https://docs.docker.com/build/cache/backends/gha/. 99 | - name: Build Runtime 100 | id: image 101 | uses: docker/build-push-action@v6 102 | with: 103 | context: . 104 | platforms: linux/${{ matrix.arch }} 105 | cache-from: type=gha 106 | cache-to: type=gha,mode=max 107 | target: image 108 | build-args: 109 | PYTHON_VERSION=${{ env.PYTHON_VERSION }} 110 | outputs: type=docker,dest=runtime-${{ matrix.arch }}.tar 111 | 112 | - name: Setup the Crossplane CLI 113 | run: "curl -sL https://raw.githubusercontent.com/crossplane/crossplane/master/install.sh | sh" 114 | 115 | - name: Build Package 116 | run: ./crossplane xpkg build --package-file=${{ matrix.arch }}.xpkg --package-root=package/ --embed-runtime-image-tarball=runtime-${{ matrix.arch }}.tar 117 | 118 | - name: Upload Single-Platform Package 119 | uses: actions/upload-artifact@v4 120 | with: 121 | name: package-${{ matrix.arch }} 122 | path: "*.xpkg" 123 | if-no-files-found: error 124 | retention-days: 1 125 | 126 | # This job downloads the single-platform packages built by the build job, and 127 | # pushes them as a multi-platform package. 128 | push: 129 | runs-on: ubuntu-24.04 130 | needs: 131 | - build 132 | steps: 133 | - name: Checkout 134 | uses: actions/checkout@v4 135 | 136 | - name: Download Single-Platform Packages 137 | uses: actions/download-artifact@v4 138 | with: 139 | # See https://github.com/docker/build-push-action/blob/263435/README.md#summaries 140 | pattern: "!*.dockerbuild" 141 | path: . 142 | merge-multiple: true 143 | 144 | - name: Setup the Crossplane CLI 145 | run: "curl -sL https://raw.githubusercontent.com/crossplane/crossplane/master/install.sh | sh" 146 | 147 | - name: Login to GitHub Container Registry 148 | uses: docker/login-action@v3 149 | with: 150 | registry: ghcr.io 151 | username: ${{ github.repository_owner }} 152 | password: ${{ secrets.GITHUB_TOKEN }} 153 | 154 | # If a version wasn't explicitly passed as a workflow_dispatch input we 155 | # default to version v0.0.0--, for example 156 | # v0.0.0-20231101115142-1091066df799. This is a simple implementation of 157 | # Go's pseudo-versions: https://go.dev/ref/mod#pseudo-versions. 158 | - name: Set Default Multi-Platform Package Version 159 | if: env.XPKG_VERSION == '' 160 | run: echo "XPKG_VERSION=v0.0.0-$(date -d@$(git show -s --format=%ct) +%Y%m%d%H%M%S)-$(git rev-parse --short=12 HEAD)" >> $GITHUB_ENV 161 | 162 | - name: Push Multi-Platform Package to GitHub Container Registry 163 | run: "./crossplane --verbose xpkg push --package-files $(echo *.xpkg|tr ' ' ,) ${{ env.XPKG }}:${{ env.XPKG_VERSION }}" 164 | -------------------------------------------------------------------------------- /.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 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 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 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1 2 | 3 | # It's important that this is Debian 12 to match the distroless image. 4 | FROM debian:12-slim AS build 5 | 6 | RUN --mount=type=cache,target=/var/lib/apt/lists \ 7 | --mount=type=cache,target=/var/cache/apt \ 8 | rm -f /etc/apt/apt.conf.d/docker-clean \ 9 | && apt-get update \ 10 | && apt-get install --no-install-recommends --yes python3-venv git 11 | 12 | # Don't write .pyc bytecode files. These speed up imports when the program is 13 | # loaded. There's no point doing that in a container where they'll never be 14 | # persisted across restarts. 15 | ENV PYTHONDONTWRITEBYTECODE=true 16 | 17 | # Use Hatch to build a wheel. The build stage must do this in a venv because 18 | # Debian doesn't have a hatch package, and it won't let you install one globally 19 | # using pip. 20 | WORKDIR /build 21 | RUN --mount=target=. \ 22 | --mount=type=cache,target=/root/.cache/pip \ 23 | python3 -m venv /venv/build \ 24 | && /venv/build/bin/pip install hatch \ 25 | && /venv/build/bin/hatch build -t wheel /whl 26 | 27 | # Create a fresh venv and install only the function wheel into it. 28 | RUN --mount=type=cache,target=/root/.cache/pip \ 29 | python3 -m venv /venv/fn \ 30 | && /venv/fn/bin/pip install /whl/*.whl 31 | 32 | # Copy the function venv to our runtime stage. It's important that the path be 33 | # the same as in the build stage, to avoid shebang paths and symlinks breaking. 34 | FROM gcr.io/distroless/python3-debian12 AS image 35 | WORKDIR / 36 | COPY --from=build /venv/fn /venv/fn 37 | EXPOSE 9443 38 | USER nonroot:nonroot 39 | ENTRYPOINT ["/venv/fn/bin/function"] 40 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # function-template-python 2 | 3 | [![CI](https://github.com/crossplane/function-template-python/actions/workflows/ci.yml/badge.svg)](https://github.com/crossplane/function-template-go/actions/workflows/ci.yml) 4 | 5 | A template for writing a [composition function][functions] in [Python][python]. 6 | 7 | To learn how to use this template: 8 | 9 | * [Follow the guide to writing a composition function in Python][function guide] 10 | * [Learn about how composition functions work][functions] 11 | * [Read the function-sdk-python package documentation][package docs] 12 | 13 | If you just want to jump in and get started: 14 | 15 | 1. Replace `function-template-python` with your function's name in 16 | `package/crossplane.yaml`. 17 | 1. Add your logic to `RunFunction` in `function/fn.py` 18 | 1. Add tests for your logic in `test/test_fn.py` 19 | 1. Update this file, `README.md`, to be about your function! 20 | 21 | This template uses [Python][python], [Docker][docker], and the [Crossplane 22 | CLI][cli] to build functions. 23 | 24 | ```shell 25 | # Run the code in development mode, for crossplane beta render 26 | hatch run development 27 | 28 | # Lint and format the code - see pyproject.toml 29 | hatch fmt 30 | 31 | # Run unit tests - see tests/test_fn.py 32 | hatch test 33 | 34 | # Build the function's runtime image - see Dockerfile 35 | $ docker build . --tag=runtime 36 | 37 | # Build a function package - see package/crossplane.yaml 38 | $ crossplane xpkg build -f package --embed-runtime-image=runtime 39 | ``` 40 | 41 | [functions]: https://docs.crossplane.io/latest/concepts/composition-functions 42 | [function guide]: https://docs.crossplane.io/knowledge-base/guides/write-a-composition-function-in-python 43 | [package docs]: https://crossplane.github.io/function-sdk-python 44 | [python]: https://python.org 45 | [docker]: https://www.docker.com 46 | [cli]: https://docs.crossplane.io/latest/cli 47 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # Example manifests 2 | 3 | You can run your function locally and test it using `crossplane beta render` 4 | with these example manifests. 5 | 6 | ```shell 7 | # Run the function locally 8 | $ hatch run development 9 | ``` 10 | 11 | ```shell 12 | # Then, in another terminal, call it with these example manifests 13 | $ crossplane beta render xr.yaml composition.yaml functions.yaml -r 14 | --- 15 | apiVersion: example.crossplane.io/v1 16 | kind: XR 17 | metadata: 18 | name: example-xr 19 | --- 20 | apiVersion: render.crossplane.io/v1beta1 21 | kind: Result 22 | message: I was run with input "Hello world"! 23 | severity: SEVERITY_NORMAL 24 | step: run-the-template 25 | ``` -------------------------------------------------------------------------------- /example/composition.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apiextensions.crossplane.io/v1 2 | kind: Composition 3 | metadata: 4 | name: function-template-python 5 | spec: 6 | compositeTypeRef: 7 | apiVersion: example.crossplane.io/v1 8 | kind: XR 9 | mode: Pipeline 10 | pipeline: 11 | - step: run-the-template 12 | functionRef: 13 | name: function-template-python 14 | input: 15 | apiVersion: template.fn.crossplane.io/v1beta1 16 | kind: Input 17 | version: v1beta2 18 | -------------------------------------------------------------------------------- /example/functions.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: pkg.crossplane.io/v1beta1 3 | kind: Function 4 | metadata: 5 | name: function-template-python 6 | annotations: 7 | # This tells crossplane beta render to connect to the function locally. 8 | render.crossplane.io/runtime: Development 9 | spec: 10 | # This is ignored when using the Development runtime. 11 | package: function-template-python -------------------------------------------------------------------------------- /example/xr.yaml: -------------------------------------------------------------------------------- 1 | # Replace this with your XR! 2 | apiVersion: example.crossplane.io/v1 3 | kind: XR 4 | metadata: 5 | name: example-xr 6 | spec: 7 | region: us-east-2 -------------------------------------------------------------------------------- /function/__version__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2023 The Crossplane Authors. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """The version of the function.""" 16 | 17 | # This is set at build time, using "hatch version" 18 | __version__ = "0.0.0" 19 | -------------------------------------------------------------------------------- /function/fn.py: -------------------------------------------------------------------------------- 1 | """A Crossplane composition function.""" 2 | 3 | import grpc 4 | from crossplane.function import logging, resource, response 5 | from crossplane.function.proto.v1 import run_function_pb2 as fnv1 6 | from crossplane.function.proto.v1 import run_function_pb2_grpc as grpcv1 7 | 8 | 9 | class FunctionRunner(grpcv1.FunctionRunnerService): 10 | """A FunctionRunner handles gRPC RunFunctionRequests.""" 11 | 12 | def __init__(self): 13 | """Create a new FunctionRunner.""" 14 | self.log = logging.get_logger() 15 | 16 | async def RunFunction( 17 | self, req: fnv1.RunFunctionRequest, _: grpc.aio.ServicerContext 18 | ) -> fnv1.RunFunctionResponse: 19 | """Run the function.""" 20 | log = self.log.bind(tag=req.meta.tag) 21 | log.info("Running function") 22 | 23 | rsp = response.to(req) 24 | 25 | version = req.input["version"] 26 | region = req.observed.composite.resource["spec"]["region"] 27 | 28 | resource.update( 29 | rsp.desired.resources["bucket"], 30 | { 31 | "apiVersion": f"s3.aws.upbound.io/{version}", 32 | "kind": "Bucket", 33 | "spec": { 34 | "forProvider": {"region": region}, 35 | }, 36 | }, 37 | ) 38 | 39 | return rsp 40 | -------------------------------------------------------------------------------- /function/main.py: -------------------------------------------------------------------------------- 1 | """The composition function's main CLI.""" 2 | 3 | import click 4 | from crossplane.function import logging, runtime 5 | 6 | from function import fn 7 | 8 | 9 | @click.command() 10 | @click.option( 11 | "--debug", 12 | "-d", 13 | is_flag=True, 14 | help="Emit debug logs.", 15 | ) 16 | @click.option( 17 | "--address", 18 | default="0.0.0.0:9443", 19 | show_default=True, 20 | help="Address at which to listen for gRPC connections", 21 | ) 22 | @click.option( 23 | "--tls-certs-dir", 24 | help="Serve using mTLS certificates.", 25 | envvar="TLS_SERVER_CERTS_DIR", 26 | ) 27 | @click.option( 28 | "--insecure", 29 | is_flag=True, 30 | help="Run without mTLS credentials. " 31 | "If you supply this flag --tls-certs-dir will be ignored.", 32 | ) 33 | def cli(debug: bool, address: str, tls_certs_dir: str, insecure: bool) -> None: # noqa:FBT001 # We only expect callers via the CLI. 34 | """A Crossplane composition function.""" 35 | try: 36 | level = logging.Level.INFO 37 | if debug: 38 | level = logging.Level.DEBUG 39 | logging.configure(level=level) 40 | runtime.serve( 41 | fn.FunctionRunner(), 42 | address, 43 | creds=runtime.load_credentials(tls_certs_dir), 44 | insecure=insecure, 45 | ) 46 | except Exception as e: 47 | click.echo(f"Cannot run function: {e}") 48 | 49 | 50 | if __name__ == "__main__": 51 | cli() 52 | -------------------------------------------------------------------------------- /package/crossplane.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: meta.pkg.crossplane.io/v1beta1 3 | kind: Function 4 | metadata: 5 | name: function-template-python 6 | spec: {} 7 | -------------------------------------------------------------------------------- /package/input/template.fn.crossplane.io_inputs.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apiextensions.k8s.io/v1 3 | kind: CustomResourceDefinition 4 | metadata: 5 | name: inputs.template.fn.crossplane.io 6 | spec: 7 | group: template.fn.crossplane.io 8 | names: 9 | categories: 10 | - crossplane 11 | kind: Input 12 | listKind: InputList 13 | plural: inputs 14 | singular: input 15 | scope: Namespaced 16 | versions: 17 | - name: v1beta1 18 | schema: 19 | openAPIV3Schema: 20 | description: Input can be used to provide input to this Function. 21 | properties: 22 | apiVersion: 23 | description: 'APIVersion defines the versioned schema of this representation 24 | of an object. Servers should convert recognized schemas to the latest 25 | internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources' 26 | type: string 27 | version: 28 | description: The bucket version to compose (e.g. v1beta2). 29 | type: string 30 | kind: 31 | description: 'Kind is a string value representing the REST resource this 32 | object represents. Servers may infer this from the endpoint the client 33 | submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds' 34 | type: string 35 | metadata: 36 | type: object 37 | required: 38 | - version 39 | type: object 40 | served: true 41 | storage: true 42 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "function" 7 | description = 'A composition function' 8 | readme = "README.md" 9 | requires-python = ">=3.11,<3.13" 10 | license = "Apache-2.0" 11 | keywords = [] 12 | authors = [{ name = "Crossplane Maintainers", email = "info@crossplane.io" }] 13 | classifiers = [ 14 | "Development Status :: 4 - Beta", 15 | "Programming Language :: Python", 16 | "Programming Language :: Python :: 3.11", 17 | "Programming Language :: Python :: 3.12", 18 | ] 19 | 20 | dependencies = [ 21 | "crossplane-function-sdk-python==0.6.0", 22 | "click==8.1.8", 23 | "grpcio==1.71.0", 24 | ] 25 | 26 | dynamic = ["version"] 27 | 28 | [project.urls] 29 | Documentation = "https://github.com/crossplane/function-template-python#readme" 30 | Issues = "https://github.com/crossplane/function-template-python/issues" 31 | Source = "https://github.com/crossplane/function-template-python" 32 | 33 | [project.scripts] 34 | function = "function.main:cli" 35 | 36 | [tool.hatch.build.targets.wheel] 37 | packages = ["function"] 38 | 39 | [tool.hatch.version] 40 | path = "function/__version__.py" 41 | validate-bump = false # Allow going from 0.0.0.dev0+x to 0.0.0.dev0+y. 42 | 43 | [tool.hatch.envs.default] 44 | type = "virtual" 45 | path = ".venv-default" 46 | dependencies = ["ipython==9.1.0"] 47 | 48 | [tool.hatch.envs.default.scripts] 49 | development = "python function/main.py --insecure --debug" 50 | 51 | # This special environment is used by hatch fmt. 52 | [tool.hatch.envs.hatch-static-analysis] 53 | dependencies = ["ruff==0.11.2"] 54 | config-path = "none" # Disable Hatch's default Ruff config. 55 | 56 | [tool.ruff] 57 | target-version = "py311" 58 | exclude = ["function/proto/*"] 59 | 60 | [tool.ruff.lint] 61 | select = [ 62 | "A", 63 | "ARG", 64 | "ASYNC", 65 | "B", 66 | "C", 67 | "D", 68 | "DTZ", 69 | "E", 70 | "EM", 71 | "ERA", 72 | "F", 73 | "FBT", 74 | "I", 75 | "ICN", 76 | "ISC", 77 | "N", 78 | "PLC", 79 | "PLE", 80 | "PLR", 81 | "PLW", 82 | "Q", 83 | "RUF", 84 | "S", 85 | "T", 86 | "TID", 87 | "UP", 88 | "W", 89 | "YTT", 90 | ] 91 | ignore = ["ISC001"] # Ruff warns this is incompatible with ruff format. 92 | 93 | [tool.ruff.lint.per-file-ignores] 94 | "tests/*" = ["D"] # Don't require docstrings for tests. 95 | 96 | [tool.ruff.lint.isort] 97 | known-first-party = ["function"] 98 | 99 | [tool.ruff.lint.pydocstyle] 100 | convention = "google" 101 | 102 | [tool.ruff.lint.pep8-naming] 103 | # gRPC requires this PascalCase function name. 104 | extend-ignore-names = ["RunFunction"] 105 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /tests/test_fn.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | import unittest 3 | 4 | from crossplane.function import logging, resource 5 | from crossplane.function.proto.v1 import run_function_pb2 as fnv1 6 | from google.protobuf import duration_pb2 as durationpb 7 | from google.protobuf import json_format 8 | from google.protobuf import struct_pb2 as structpb 9 | 10 | from function import fn 11 | 12 | 13 | class TestFunctionRunner(unittest.IsolatedAsyncioTestCase): 14 | def setUp(self) -> None: 15 | # Allow larger diffs, since we diff large strings of JSON. 16 | self.maxDiff = 2000 17 | 18 | logging.configure(level=logging.Level.DISABLED) 19 | 20 | async def test_run_function(self) -> None: 21 | @dataclasses.dataclass 22 | class TestCase: 23 | reason: str 24 | req: fnv1.RunFunctionRequest 25 | want: fnv1.RunFunctionResponse 26 | 27 | cases = [ 28 | TestCase( 29 | reason="The function should return the input as a result.", 30 | req=fnv1.RunFunctionRequest( 31 | input=resource.dict_to_struct({"version": "v1beta2"}), 32 | observed=fnv1.State( 33 | composite=fnv1.Resource( 34 | resource=resource.dict_to_struct( 35 | { 36 | "apiVersion": "example.crossplane.io/v1", 37 | "kind": "XR", 38 | "spec": {"region": "us-west-2"}, 39 | } 40 | ), 41 | ), 42 | ), 43 | ), 44 | want=fnv1.RunFunctionResponse( 45 | meta=fnv1.ResponseMeta(ttl=durationpb.Duration(seconds=60)), 46 | desired=fnv1.State( 47 | resources={ 48 | "bucket": fnv1.Resource( 49 | resource=resource.dict_to_struct( 50 | { 51 | "apiVersion": "s3.aws.upbound.io/v1beta2", 52 | "kind": "Bucket", 53 | "spec": { 54 | "forProvider": {"region": "us-west-2"}, 55 | }, 56 | } 57 | ), 58 | ), 59 | }, 60 | ), 61 | context=structpb.Struct(), 62 | ), 63 | ), 64 | ] 65 | 66 | runner = fn.FunctionRunner() 67 | 68 | for case in cases: 69 | got = await runner.RunFunction(case.req, None) 70 | self.assertEqual( 71 | json_format.MessageToDict(case.want), 72 | json_format.MessageToDict(got), 73 | "-want, +got", 74 | ) 75 | 76 | 77 | if __name__ == "__main__": 78 | unittest.main() 79 | --------------------------------------------------------------------------------