├── .github └── workflows │ └── build.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── bin ├── pulumilocal └── pulumilocal.bat ├── setup.cfg ├── setup.py └── tests ├── __init__.py └── test_apply.py /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: 2 | workflow_dispatch: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | branches: 8 | - main 9 | 10 | name: Build and Test 11 | jobs: 12 | build_test: 13 | timeout-minutes: 60 14 | runs-on: ubuntu-latest 15 | env: 16 | AWS_DEFAULT_REGION: us-east-1 17 | PYTHONUNBUFFERED: 1 18 | 19 | steps: 20 | - name: Check out code 21 | uses: actions/checkout@v3 22 | 23 | - name: Start LocalStack 24 | uses: LocalStack/setup-localstack@v0.1.2 25 | with: 26 | image-tag: 'latest' 27 | 28 | - name: Install Pulumi CLI 29 | uses: pulumi/setup-pulumi@v2 30 | - name: Set up Python 3.12 31 | uses: actions/setup-python@v2 32 | with: 33 | python-version: '3.12' 34 | 35 | - name: Install dependencies 36 | run: make install 37 | 38 | - name: Run code linter 39 | run: make lint 40 | 41 | - name: Run tests 42 | run: make test 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Custom 2 | *.pyc 3 | 4 | Pulumi.* 5 | myproj 6 | 7 | .env 8 | .envrc 9 | 10 | # Byte-compiled / optimized / DLL files 11 | __pycache__/ 12 | *.py[cod] 13 | *$py.class 14 | 15 | # C extensions 16 | *.so 17 | 18 | # Distribution / packaging 19 | .Python 20 | build/ 21 | develop-eggs/ 22 | dist/ 23 | downloads/ 24 | eggs/ 25 | .eggs/ 26 | lib/ 27 | lib64/ 28 | parts/ 29 | sdist/ 30 | var/ 31 | wheels/ 32 | share/python-wheels/ 33 | *.egg-info/ 34 | .installed.cfg 35 | *.egg 36 | MANIFEST 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .nox/ 52 | .coverage 53 | .coverage.* 54 | .cache 55 | nosetests.xml 56 | coverage.xml 57 | *.cover 58 | *.py,cover 59 | .hypothesis/ 60 | .pytest_cache/ 61 | cover/ 62 | 63 | # Translations 64 | *.mo 65 | *.pot 66 | 67 | # Django stuff: 68 | *.log 69 | local_settings.py 70 | db.sqlite3 71 | db.sqlite3-journal 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # PyBuilder 84 | .pybuilder/ 85 | target/ 86 | 87 | # Jupyter Notebook 88 | .ipynb_checkpoints 89 | 90 | # IPython 91 | profile_default/ 92 | ipython_config.py 93 | 94 | # pyenv 95 | # For a library or package, you might want to ignore these files since the code is 96 | # intended to run in multiple environments; otherwise, check them in: 97 | .python-version 98 | 99 | # pipenv 100 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 101 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 102 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 103 | # install all needed dependencies. 104 | #Pipfile.lock 105 | 106 | # poetry 107 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 108 | # This is especially recommended for binary packages to ensure reproducibility, and is more 109 | # commonly ignored for libraries. 110 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 111 | #poetry.lock 112 | 113 | # pdm 114 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 115 | #pdm.lock 116 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 117 | # in version control. 118 | # https://pdm.fming.dev/#use-with-ide 119 | .pdm.toml 120 | 121 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 122 | __pypackages__/ 123 | 124 | # Celery stuff 125 | celerybeat-schedule 126 | celerybeat.pid 127 | 128 | # SageMath parsed files 129 | *.sage.py 130 | 131 | # Environments 132 | .env 133 | .venv 134 | env/ 135 | venv/ 136 | ENV/ 137 | env.bak/ 138 | venv.bak/ 139 | 140 | # Spyder project settings 141 | .spyderproject 142 | .spyproject 143 | 144 | # Rope project settings 145 | .ropeproject 146 | 147 | # mkdocs documentation 148 | /site 149 | 150 | # mypy 151 | .mypy_cache/ 152 | .dmypy.json 153 | dmypy.json 154 | 155 | # Pyre type checker 156 | .pyre/ 157 | 158 | # pytype static type analyzer 159 | .pytype/ 160 | 161 | # Cython debug symbols 162 | cython_debug/ 163 | 164 | # PyCharm 165 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 166 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 167 | # and can be added to the global gitignore or merged into this file. For a more nuclear 168 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 169 | .idea/ 170 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VENV_BIN ?= virtualenv 2 | # Default virtual env dir 3 | VENV_DIR ?= .venv 4 | PIP_CMD ?= pip3 5 | TEST_PATH ?= tests 6 | 7 | ifeq ($(OS), Windows_NT) 8 | VENV_ACTIVATE = ./$(VENV_DIR)/Scripts/activate 9 | else 10 | VENV_ACTIVATE = ./$(VENV_DIR)/bin/activate 11 | endif 12 | 13 | VENV_RUN = . $(VENV_ACTIVATE) 14 | 15 | venv: ## Create a virtual environment 16 | (test `which virtualenv`|| $(PIP_CMD) install --user virtualenv) && \ 17 | (test -d $(VENV_DIR) || $(VENV_BIN) $(VENV_OPTS) $(VENV_DIR)) 18 | 19 | usage: ## Show this help 20 | @fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//' 21 | 22 | install: venv ## Install dependencies in local virtualenv folder 23 | $(VENV_RUN); $(PIP_CMD) install -e .[test] 24 | 25 | publish: venv ## Publish the library to the central PyPi repository 26 | # build and upload archive 27 | $(VENV_RUN); $(PIP_CMD) install --upgrade setuptools wheel twine 28 | (./setup.py sdist && twine upload --repository pulumi-local dist/*) 29 | 30 | lint: venv ## Run code linter 31 | $(VENV_RUN); flake8 --ignore=E501,W503 bin/pulumilocal tests 32 | 33 | test: venv ## Run unit/integration tests 34 | $(VENV_RUN); pytest $(PYTEST_ARGS) -sv $(TEST_PATH) 35 | 36 | clean: ## Clean up 37 | rm -rf $(VENV_DIR) 38 | rm -rf dist 39 | rm -rf *.egg-info 40 | 41 | .PHONY: clean publish install usage lint test venv -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Pulumi CLI for LocalStack 2 | 3 | **DISCLAIMER: pulumi-local currently does not support the _aws-native_ package. ([pulumi/pulumi-aws-native #108](https://github.com/pulumi/pulumi-aws-native/issues/108))** 4 | 5 | This package provides the `pulumilocal` command, which is a thin wrapper around the `pulumi` 6 | command line interface to use [`Pulumi`](https://github.com/pulumi/pulumi) with [LocalStack](https://github.com/localstack/localstack). 7 | 8 | ## Installation 9 | 10 | You can install the `pulumilocal` command via `pip`: 11 | 12 | ``` 13 | pip install pulumi-local 14 | ``` 15 | 16 | ## Prerequisites 17 | 18 | Please make sure you have a LocalStack instance running on your local machine. 19 | 20 | ## Usage 21 | 22 | The `pulumilocal` command has the same usage as the `pulumi` command. For detailed usage, 23 | please refer to the man pages of `pulumi -h`. 24 | 25 | ### Add environment variables to store state on local backend (optional) 26 | ```shell 27 | export PULUMI_CONFIG_PASSPHRASE=lsdevtest 28 | export PULUMI_BACKEND_URL=file://`pwd`/myproj 29 | ``` 30 | _Note: For further options please consult the official documentation on available [environment variables][env_vars] and [local backend][local_backend]._ 31 | 32 | [env_vars]: https://www.pulumi.com/docs/cli/environment-variables/ 33 | [local_backend]: https://www.pulumi.com/docs/concepts/state/#local-filesystem 34 | 35 | ### Create a new Pulumi project with stack name lsdev 36 | ```shell 37 | mkdir myproj 38 | pulumilocal new typescript -y -s lsdev --cwd myproj 39 | ``` 40 | _Note: `--cwd` switch is unnecessary if commands are being run in project directory._ 41 | 42 | ### Select and create the lsdev Pulumi stack 43 | This is unnecessary if you just did the `new typescript` command above as it will already be selected. 44 | ```shell 45 | pulumilocal stack select -c lsdev --cwd myproj 46 | ``` 47 | 48 | ### Deploy the stack to LocalStack 49 | ```shell 50 | pulumilocal up --cwd myproj 51 | ``` 52 | 53 | ## How it works 54 | 55 | When running any pulumi deployment command like `pulumilocal ["up", "destroy", "preview", "cancel"]`, 56 | the wrapper script runs the `pulumi config` command to augment the pulumi config with LocalStack AWS configuration, 57 | and then runs the original pulumi command. 58 | 59 | ## Configurations 60 | 61 | You can configure the following environment variables: 62 | 63 | * `AWS_ENDPOINT_URL`: hostname and port of the target LocalStack instance 64 | * `LOCALSTACK_HOSTNAME`: __(Deprecated)__ Target host to use for connecting to LocalStack (default: `localhost`) 65 | * `EDGE_PORT`: __(Deprecated)__ Target port to use for connecting to LocalStack (default: `4566`) 66 | * `PULUMI_CMD`: Name of the executable Pulumi command on the system PATH (default: `pulumi`) 67 | * `CONFIG_STRATEGY`: the strategy to handle config merging. If stack config already exists `pulumi-local` will prompt for user input. Possible values are: 68 | * `overwrite` (default): pulumi-local will overwrite the stack's config and replaces it with values necessary to communicate with LocalStack. This strategy is equivalent of the legacy behaviour. 69 | * `override`: generates a temporary config file from the current stack config and overrides it's values, after run this file will be deleted. The name of the file is generated from the `LS_STACK_NAME` variable. 70 | * `separate`: creates a separate stack with the stack name set in the `LS_STACK_NAME` env variable. 71 | > [!NOTE] 72 | > The fall through to the default strategy with a misconfigured or missing `CONFIG_STRATEGY` environment variable will be deprecated by the next `pulumi-local` version. 73 | * `LS_STACK_NAME`: the stack name to use when the config file generated either with the `override` and `separate` strategy. 74 | * `DRY_RUN`: only usable with `CONFIG_STRATEGY=override`, as a result the created temporary stack config is not deleted. 75 | * `NON_INTERACTIVE`: starts a non-interactive session where all user prompts are automatically accepted 76 | 77 | > [!WARNING] 78 | > Using the `DRY_RUN` and `NON_INTERACTIVE` flags together changes the stack configuration without confirmation prompt. Use with caution! 79 | 80 | ## Deploying to AWS 81 | Use your preferred Pulumi backend. https://www.pulumi.com/docs/concepts/state/#deciding-on-a-state-backend 82 | Change the `pulumilocal` command in the instructions above to `pulumi`. 83 | 84 | ## Change Log 85 | 86 | * v1.3.0: Add config merging strategies, dry-run and non-interactive runs. 87 | * v1.2.2: Fix project URL in package metadata 88 | * v1.2.1: Add support for AWS_ENDPOINT_URL env variable 89 | * v1.2.0: Added dynamic endpoint generation and tests 90 | * v1.1: Added README to long description and update twine publish. 91 | * v1.0: Using `pulumi config set-all` to set all the AWS provider configurating instead of modifying 92 | the Stack file directly. Removed defaulting the stack name to `localstack`. Added argparse. 93 | Removed pyyaml dependency. Removed python2 package classifiers. 94 | * v0.6: Replace deprecated `s3ForcePathStyle` with `s3UsePathStyle` in default config 95 | * v0.5: Remove deprecated `mobileanalytics` service config to fix invalid key error 96 | * v0.4: Point pulumilocal.bat to the correct script 97 | * v0.3: Add apigatewayv2 service endpoint 98 | * v0.2: Add init command and add aws:region key by default 99 | * v0.1: Initial release 100 | 101 | ## License 102 | 103 | This software library is released under the Apache License, Version 2.0 (see `LICENSE`). 104 | 105 | [pypi-version]: https://img.shields.io/pypi/v/pulumi-local.svg 106 | [pypi]: https://pypi.org/project/pulumi-local/ 107 | -------------------------------------------------------------------------------- /bin/pulumilocal: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Thin wrapper around the "pulumi" command line interface (CLI) to use 5 | Pulumi (https://pulumi.com) with LocalStack (https://localstack.cloud). 6 | 7 | Options: 8 | Run "pulumi -h" for more details on the pulumi CLI subcommands. 9 | """ 10 | 11 | import os 12 | import sys 13 | import argparse 14 | import subprocess 15 | import json 16 | from typing import Dict, List 17 | from shutil import copyfile 18 | from urllib.parse import urlparse 19 | from shutil import which 20 | import functools 21 | 22 | 23 | # force unbuffered print 24 | print = functools.partial(print, flush=True) 25 | 26 | # for local testing 27 | PARENT_FOLDER = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) 28 | if os.path.isdir(os.path.join(PARENT_FOLDER, ".venv")): 29 | sys.path.insert(0, PARENT_FOLDER) 30 | 31 | # define global constants 32 | TRUE_STRINGS = ["1", "true"] 33 | CONFIG_STRATEGIES = ("overwrite", "override", "separation") 34 | DEFAULT_CONFIG_STRATEGY = "overwrite" 35 | LS_STACK_NAME = os.environ.get("LS_STACK_NAME") or "localstack" 36 | CONFIG_STRATEGY = os.environ.get("CONFIG_STRATEGY") if os.environ.get("CONFIG_STRATEGY") in CONFIG_STRATEGIES else DEFAULT_CONFIG_STRATEGY 37 | PULUMI_CMD = os.environ.get("PULUMI_CMD") or "pulumi" 38 | AWS_ENDPOINT_URL = os.environ.get("AWS_ENDPOINT_URL") 39 | LOCALSTACK_HOSTNAME = urlparse(os.environ.get("AWS_ENDPOINT_URL")).hostname or os.environ.get("LOCALSTACK_HOSTNAME") or "localhost" 40 | EDGE_PORT = int(urlparse(os.environ.get("AWS_ENDPOINT_URL")).port or os.environ.get("EDGE_PORT") or 4566) 41 | USE_SSL = str(os.environ.get("USE_SSL", "")).strip().lower() in TRUE_STRINGS 42 | DRY_RUN = str(os.environ.get("DRY_RUN", "")).strip().lower() in TRUE_STRINGS 43 | NON_INTERACTIVE = str(os.environ.get("NON_INTERACTIVE", "")).strip().lower() in TRUE_STRINGS 44 | PROXIED_CMDS = ( 45 | "up", 46 | "destroy", 47 | "preview", 48 | "cancel" 49 | ) 50 | 51 | 52 | # Do not allow PULUMI_CMD env var to be set to pulumilocal as this causes an error 53 | if PULUMI_CMD == "pulumilocal": 54 | PULUMI_CMD = "pulumi" 55 | 56 | # Look up path 57 | PULUMI_CMD = which(PULUMI_CMD) 58 | 59 | 60 | def deactivate_access_key(access_key: str) -> str: 61 | """Safe guarding user from accidental live credential usage by deactivating access key IDs. 62 | See more: https://docs.localstack.cloud/references/credentials/""" 63 | return "L" + access_key[1:] if access_key[0] == "A" else access_key 64 | 65 | 66 | def get_stack_config_file_path(args: argparse.Namespace) -> str: 67 | """Determine the path under which the stack config file should exist""" 68 | if args.config_file and os.path.isabs(args.config_file): 69 | return args.config_file 70 | 71 | base_dir = args.cwd or "." 72 | stack_config = args.config_file or f"Pulumi.{args.stack}.yaml" 73 | 74 | return os.path.join(base_dir, stack_config) 75 | 76 | 77 | def check_stack_config_file(stack_config: str) -> None: 78 | """Checks stack config file existance""" 79 | if os.path.exists(stack_config): 80 | msg = f"Stack config file {stack_config} already exists" 81 | err_msg = msg + " - please delete it first, exiting..." 82 | if CONFIG_STRATEGY == "overwrite": 83 | msg += ". File will be overwritten." 84 | print(msg) 85 | print("\tOnly 'yes' will be accepted to approve.") 86 | if input("\tEnter a value: ") == "yes": 87 | return 88 | print(err_msg, file=sys.stderr) 89 | exit(1) 90 | 91 | 92 | def generate_service_endpoints(args) -> Dict: 93 | """Generate service list from the schema of the currently used AWS package 94 | """ 95 | cmd_args = [PULUMI_CMD, "about", "--json"] 96 | if args.cwd: 97 | cmd_args.extend(("--cwd", args.cwd)) 98 | try: 99 | sp = subprocess.run(executable=PULUMI_CMD, args=cmd_args, check=True, bufsize=0, capture_output=True) 100 | except subprocess.CalledProcessError as e: 101 | exit(e.returncode) 102 | plugins = json.loads(sp.stdout.decode("utf-8")).get("plugins") 103 | try: 104 | version = "@" + next(filter(lambda plugin: plugin["name"] == "aws", plugins)).get("version") 105 | except (TypeError, StopIteration): 106 | version = "" 107 | config_args = [PULUMI_CMD, "package", "get-schema", f"aws{version}"] 108 | try: 109 | sp = subprocess.run(executable=PULUMI_CMD, args=config_args, check=True, bufsize=0, capture_output=True) 110 | except subprocess.CalledProcessError as e: 111 | exit(e.returncode) 112 | schema = json.loads(sp.stdout.decode("utf-8")) 113 | services = list(schema["types"]["aws:config/endpoints:endpoints"]["properties"].keys()) 114 | return services 115 | 116 | 117 | def get_service_endpoint() -> str: 118 | protocol = "https" if USE_SSL else "http" 119 | endpoint = "%s://%s:%s" % (protocol, LOCALSTACK_HOSTNAME, EDGE_PORT) 120 | return endpoint 121 | 122 | 123 | def set_config_options(is_path: bool = False, is_secret: bool = False, **kwargs: Dict) -> List: 124 | args = [] 125 | for option, value in kwargs.items(): 126 | if is_path: 127 | args.append("--path") 128 | if is_secret: 129 | args.append("--secret") 130 | else: 131 | args.append("--plaintext") 132 | args.append(f"{option}={value}") 133 | return args 134 | 135 | 136 | def set_localstack_pulumi_config(args: argparse.Namespace): 137 | # LocalStack Endpoint 138 | service_url = get_service_endpoint() 139 | # Create argument list to pulumi config set-all 140 | config_args = list() 141 | config_args.append(PULUMI_CMD) 142 | config_args.append("config") 143 | # If stack arg was supplied, add it to config command 144 | if args.stack: 145 | config_args.append("--stack") 146 | config_args.append(args.stack) 147 | # If cwd arg was supplied, add it to config command 148 | if args.cwd: 149 | config_args.append("--cwd") 150 | config_args.append(args.cwd) 151 | if args.config_file: 152 | config_args.append("--config-file") 153 | config_args.append(args.config_file) 154 | 155 | # Resetting all endpoints 156 | try: 157 | subprocess.run( 158 | executable=PULUMI_CMD, 159 | args=(config_args + ["set-all"] + set_config_options(is_path=True, **{"aws:endpoints": ""})), 160 | check=True, 161 | bufsize=0, 162 | ) 163 | except subprocess.CalledProcessError as e: 164 | exit(e.returncode) 165 | except FileNotFoundError as e: 166 | print(e, file=sys.stderr) 167 | exit(e.errno) 168 | 169 | DEFAULT_CONFIG_ARGS = { 170 | "aws:region": "us-east-1", 171 | "aws:accessKey": "test", 172 | "aws:secretKey": "test", 173 | "aws:s3UsePathStyle": "true", 174 | "aws:skipCredentialsValidation": "true", 175 | "aws:skipRequestingAccountId": "true", 176 | } 177 | 178 | tmp = DEFAULT_CONFIG_ARGS.copy() 179 | for k in DEFAULT_CONFIG_ARGS: 180 | try: 181 | output = subprocess.run( 182 | executable=PULUMI_CMD, 183 | args=(config_args + ["get", k]), 184 | stderr=subprocess.DEVNULL, 185 | stdout=subprocess.PIPE, 186 | check=True, 187 | bufsize=0, 188 | ).stdout.decode("utf-8").strip("\n") 189 | except subprocess.CalledProcessError: 190 | pass 191 | else: 192 | if k == "aws:accessKey": 193 | tmp[k] = deactivate_access_key(output) 194 | elif k != "aws:secretKey": 195 | del tmp[k] 196 | DEFAULT_CONFIG_ARGS = tmp 197 | 198 | config_args.append("set-all") 199 | config_args.extend(set_config_options(**DEFAULT_CONFIG_ARGS)) 200 | for idx, service in enumerate(generate_service_endpoints(args)): 201 | config_args.extend(set_config_options(is_path=True, **{f"aws:endpoints[{idx}].{service}": service_url})) 202 | try: 203 | subprocess.run(executable=PULUMI_CMD, args=config_args, check=True, bufsize=0) 204 | except subprocess.CalledProcessError as e: 205 | exit(e.returncode) 206 | 207 | 208 | def main(): 209 | # Parse arguments from call to pulumi CLI that set the stack name and directory 210 | parser = argparse.ArgumentParser(add_help=False) 211 | parser.add_argument("command", help="Pulumi command", 212 | type=str, nargs="?") 213 | parser.add_argument("-s", "--stack", help="The name of the stack to operate on. Defaults to the current stack", 214 | required=False, 215 | type=str) 216 | parser.add_argument("-C", "--cwd", help="Run pulumi as if it had been started in another directory", 217 | required=False, 218 | type=str) 219 | parser.add_argument("--config-file", help="Use the configuration values in the specified file rather than detecting the file name", 220 | required=False, 221 | type=str) 222 | parser.add_argument("--non-interactive", help="Disable interactive mode for all commands", 223 | action="store_true", 224 | required=False) 225 | args, _ = parser.parse_known_args() 226 | 227 | if NON_INTERACTIVE: 228 | args.non_interactive = True 229 | 230 | if not args.cwd: 231 | args.cwd = "." 232 | 233 | if os.environ.get("CONFIG_STRATEGY") not in CONFIG_STRATEGIES: 234 | print(f"Config strategy: {os.environ.get('CONFIG_STRATEGY')}") 235 | print(f'Config strategy is not recognised. Falling back to default ("{DEFAULT_CONFIG_STRATEGY}").') 236 | 237 | # If this is a pulumi deployment command, update the stack with LocalStack AWS config 238 | if args.command in PROXIED_CMDS: 239 | if not args.stack: 240 | try: 241 | args.stack = subprocess.run( 242 | [PULUMI_CMD, "stack", "--show-name", "--non-interactive", "-C", args.cwd], 243 | check=True, 244 | capture_output=True, 245 | bufsize=0, 246 | ).stdout.decode("utf-8").strip("\n") 247 | except (subprocess.CalledProcessError) as e: 248 | print(e.stderr.decode("utf-8"), file=sys.stderr) 249 | exit(1) 250 | config_file_path = get_stack_config_file_path(args) 251 | if not args.non_interactive: 252 | check_stack_config_file(config_file_path) 253 | if CONFIG_STRATEGY == "override": 254 | override_config_file = os.path.join(os.path.dirname(config_file_path), f"Pulumi.{LS_STACK_NAME}.yaml") 255 | copyfile(src=config_file_path, dst=override_config_file) 256 | args.config_file = override_config_file 257 | elif CONFIG_STRATEGY == "separation": 258 | print(f"Creating stack {LS_STACK_NAME}, if not existing...") 259 | subprocess.run( 260 | [PULUMI_CMD, "stack", "init", "--non-interactive", "-s", LS_STACK_NAME, "-C", args.cwd], 261 | check=False, 262 | stderr=subprocess.DEVNULL, 263 | bufsize=0, 264 | ) 265 | override_config_file = os.path.join(os.path.dirname(config_file_path), f"Pulumi.{LS_STACK_NAME}.yaml") 266 | if override_config_file != config_file_path: 267 | copyfile(src=config_file_path, dst=override_config_file) 268 | args.config_file = override_config_file 269 | print("Updating this Stack with LocalStack config") 270 | set_localstack_pulumi_config(args) 271 | # Run the original command 272 | if DRY_RUN and args.command in PROXIED_CMDS: 273 | print("Dry run detected, skipping Pulumi invokation. Terminating.") 274 | else: 275 | if args.non_interactive and "--non-interactive" not in sys.argv: 276 | sys.argv.append("--non-interactive") 277 | try: 278 | subprocess.run(executable=PULUMI_CMD, args=sys.argv, check=True, bufsize=0) 279 | except subprocess.CalledProcessError as e: 280 | print(e.stderr.decode("utf-8"), file=sys.stderr) 281 | finally: 282 | if CONFIG_STRATEGY == "override" and args.command in PROXIED_CMDS: 283 | os.remove(args.config_file) 284 | 285 | 286 | if __name__ == "__main__": 287 | main() 288 | -------------------------------------------------------------------------------- /bin/pulumilocal.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | python "%~dp0\pulumilocal" %* 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = pulumi-local 3 | version = 1.3.0 4 | url = https://github.com/localstack/pulumi-local 5 | author = LocalStack Team 6 | author_email = info@localstack.cloud 7 | description = Thin wrapper script to use Pulumi with LocalStack 8 | long_description = file: README.md 9 | long_description_content_type = text/markdown 10 | license = Apache License 2.0 11 | classifiers = 12 | Programming Language :: Python :: 3 13 | Programming Language :: Python :: 3.8 14 | Programming Language :: Python :: 3.9 15 | Programming Language :: Python :: 3.10 16 | Programming Language :: Python :: 3.11 17 | Programming Language :: Python :: 3.12 18 | License :: OSI Approved :: Apache Software License 19 | Topic :: Software Development :: Testing 20 | 21 | [options] 22 | zip_safe = False 23 | scripts = 24 | bin/pulumilocal 25 | bin/pulumilocal.bat 26 | packages = find: 27 | 28 | [options.extras_require] 29 | test = 30 | flake8 31 | localstack 32 | pytest 33 | boto3 34 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup 4 | 5 | setup() 6 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/localstack/pulumi-local/4f86f28bf834bbdd2c3abfc5f526cd163dc9ca86/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_apply.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import tempfile 4 | import uuid 5 | from typing import Dict, Tuple 6 | import boto3 7 | import pytest 8 | from shutil import rmtree 9 | 10 | THIS_PATH = os.path.abspath(os.path.dirname(__file__)) 11 | ROOT_PATH = os.path.join(THIS_PATH, "..") 12 | PULUMILOCAL_BIN = os.path.join(ROOT_PATH, "bin", "pulumilocal") 13 | LOCALSTACK_ENDPOINT = "http://localhost.localstack.cloud:4566" 14 | 15 | 16 | @pytest.mark.parametrize("package_version", ["5.42.0", "latest"]) 17 | @pytest.mark.parametrize("select_stack", [True, False]) 18 | @pytest.mark.parametrize("select_cwd", [True, False]) 19 | def test_provisioning(package_version: str, select_stack: bool, select_cwd: bool): 20 | # create bucket 21 | bucket_name = short_uid() 22 | create_test_bucket(bucket_name, package_version, select_stack, select_cwd) 23 | s3_bucket_names = get_bucket_names() 24 | 25 | # Pulumi adds suffix to the bucket's name so not enough simply checking for the name in the list 26 | assert any(s3_bucket.startswith(bucket_name) for s3_bucket in s3_bucket_names) 27 | 28 | 29 | def test_provisioning_outside_project(): 30 | # create bucket 31 | bucket_name = short_uid() 32 | assert "error: no Pulumi.yaml project file found" in create_test_bucket(bucket_name, should_fail=True) 33 | 34 | 35 | @pytest.mark.parametrize("config_strategy", ["override", "overwrite", "separation", "separate", ""]) 36 | def test_config_strategy(config_strategy: str): 37 | env_vars = { 38 | "PULUMI_CONFIG_PASSPHRASE": "localstack", 39 | "NON_INTERACTIVE": "1", 40 | } 41 | if config_strategy: 42 | env_vars.update({"CONFIG_STRATEGY": config_strategy}) 43 | try: 44 | tmp_dir = create_dummy_stack(env_vars=env_vars) 45 | match config_strategy: 46 | case "override": 47 | stack_configs = { 48 | os.path.join(tmp_dir, "Pulumi.localstack.yaml"): (False, False), 49 | os.path.join(tmp_dir, "Pulumi.test.yaml"): (True, False) 50 | } 51 | case "separation": 52 | stack_configs = { 53 | os.path.join(tmp_dir, "Pulumi.localstack.yaml"): (True, True), 54 | os.path.join(tmp_dir, "Pulumi.test.yaml"): (True, False) 55 | } 56 | case _: 57 | stack_configs = { 58 | os.path.join(tmp_dir, "Pulumi.localstack.yaml"): (False, False), 59 | os.path.join(tmp_dir, "Pulumi.test.yaml"): (True, True) 60 | } 61 | 62 | for stack_config, expected_result in stack_configs.items(): 63 | should_exists = expected_result[0] 64 | local_config = expected_result[1] 65 | assert os.path.exists(stack_config) == should_exists 66 | if should_exists and local_config: 67 | run_result = run([PULUMILOCAL_BIN, "config", "get", "aws:secretKey", "--cwd", tmp_dir, "--config-file", stack_config], env={**os.environ, **env_vars}) 68 | print(run_result) 69 | assert run_result[1].strip("\n").split("\n")[-1] == "test" 70 | elif should_exists and not local_config: 71 | run_result = run([PULUMILOCAL_BIN, "config", "get", "aws:secretKey", "--cwd", tmp_dir, "--config-file", stack_config], env={**os.environ, **env_vars}) 72 | print(run_result) 73 | assert run_result[0] 74 | finally: 75 | if os.path.exists(tmp_dir): 76 | rmtree(tmp_dir) 77 | 78 | ### 79 | # UTIL FUNCTIONS 80 | ### 81 | 82 | 83 | def deploy_pulumi_script(script: str, version: str, select_stack: bool, select_cwd: bool, env_vars: Dict[str, str] = None, should_fail: bool = False, cleanup: bool = True) -> str: 84 | kwargs = {} 85 | with tempfile.TemporaryDirectory(delete=cleanup) as temp_dir: 86 | if not select_cwd and not should_fail: 87 | kwargs["cwd"] = temp_dir 88 | env_vars.update({ 89 | "PULUMI_BACKEND_URL": f"file://{temp_dir}" 90 | }) 91 | kwargs["env"] = {**os.environ, **(env_vars or {})} 92 | 93 | cmd = [PULUMILOCAL_BIN, "new", "typescript", "-y", "-s", "test", "--cwd", temp_dir] 94 | out = run(cmd, **kwargs) 95 | if out[0]: 96 | return out[1] 97 | 98 | cmd = ["npm", "install", f"@pulumi/aws{'@' + version}", "--prefix", temp_dir] 99 | out = run(cmd, **kwargs) 100 | if out[0]: 101 | return out[1] 102 | 103 | with open(os.path.join(temp_dir, "index.ts"), "w") as f: 104 | f.write(script) 105 | 106 | # To test short switches too 107 | cmd = [PULUMILOCAL_BIN, "preview"] 108 | if select_stack and not should_fail: 109 | cmd.extend(["-s", "test"]) 110 | if select_cwd and not should_fail: 111 | cmd.extend(["-C", temp_dir]) 112 | out = run(cmd, **kwargs) 113 | if out[0]: 114 | return out[1] 115 | 116 | cmd = [PULUMILOCAL_BIN, "up", "-y"] 117 | if select_stack and not should_fail: 118 | cmd.extend(["--stack", "test"]) 119 | if select_cwd and not should_fail: 120 | cmd.extend(["--cwd", temp_dir]) 121 | out = run(cmd, **kwargs) 122 | return temp_dir 123 | 124 | 125 | def create_dummy_stack(env_vars: Dict) -> str: 126 | config = """import * as pulumi from "@pulumi/pulumi";""" 127 | return deploy_pulumi_script( 128 | config, 129 | version="latest", 130 | select_stack=False, 131 | select_cwd=False, 132 | env_vars=env_vars, 133 | cleanup=False 134 | ) 135 | 136 | 137 | def create_test_bucket(bucket_name: str, version: str = "latest", select_stack: bool = False, select_cwd: bool = False, should_fail: bool = False) -> str: 138 | config = """import * as pulumi from "@pulumi/pulumi"; 139 | import * as aws from "@pulumi/aws"; 140 | 141 | const bucket = new aws.s3.Bucket("%s"); 142 | 143 | export const bucketName = bucket.id; 144 | """ % (bucket_name) 145 | return deploy_pulumi_script( 146 | config, 147 | version=version, 148 | select_stack=select_stack, 149 | select_cwd=select_cwd, 150 | env_vars={"PULUMI_CONFIG_PASSPHRASE": "localstack", "NON_INTERACTIVE": "1"}, 151 | should_fail=should_fail, 152 | ) 153 | 154 | 155 | def get_bucket_names(**kwargs: dict) -> list: 156 | s3 = client("s3", region_name="us-east-1", **kwargs) 157 | s3_buckets = s3.list_buckets().get("Buckets") 158 | return [s["Name"] for s in s3_buckets] 159 | 160 | 161 | def short_uid() -> str: 162 | return str(uuid.uuid4())[0:8] 163 | 164 | 165 | def client(service: str, **kwargs): 166 | # if aws access key is not set AND no profile is in the environment, 167 | # we want to set the access key and the secret key to test 168 | if "aws_access_key_id" not in kwargs and "AWS_PROFILE" not in os.environ: 169 | kwargs["aws_access_key_id"] = "test" 170 | if "aws_access_key_id" in kwargs and "aws_secret_access_key" not in kwargs: 171 | kwargs["aws_secret_access_key"] = "test" 172 | boto3.setup_default_session() 173 | return boto3.client( 174 | service, 175 | endpoint_url=LOCALSTACK_ENDPOINT, 176 | **kwargs, 177 | ) 178 | 179 | 180 | def run(cmd, **kwargs) -> Tuple: 181 | try: 182 | kwargs["stderr"] = subprocess.STDOUT 183 | kwargs["stdout"] = subprocess.PIPE 184 | sp = subprocess.run(cmd, **kwargs, check=True) 185 | return (sp.returncode, sp.stdout.decode("utf-8")) 186 | except subprocess.CalledProcessError as e: 187 | return (e.returncode, e.stdout.decode("utf-8")) 188 | --------------------------------------------------------------------------------