diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 130097e..259d50b 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -17,6 +17,10 @@ concurrency: env: PYTHON_VERSION: "3.13" KUBECONFORM_VERSION: "v0.7.0" + # Checks the CloudFormation converter's output. From terraform__SHA256SUMS on + # releases.hashicorp.com; update both together. + TERRAFORM_VERSION: "1.17.2" + TERRAFORM_SHA256: "e6f16b2f0b137ee5729caa8c4e79a3bae4ee261acd198a1fcfa8584a6296605b" # Every service under services/ (and k8s/). Jobs loop over this list, so the check names # the branch ruleset requires stay the same when a service is added. SERVICES: converter-api web @@ -39,6 +43,11 @@ jobs: echo "== $service" (cd "services/$service" && ruff check . && ruff format --check .) done + # The rules ruff has no setting for: no nested functions or lambdas, no * or **, + # imports at the top only, no silenced checks, docstrings and return types, and the + # writing rules for the docs. See scripts/check_code_rules.py. + - name: House code rules + run: python scripts/check_code_rules.py test: runs-on: ubuntu-latest @@ -94,6 +103,8 @@ jobs: curl -fsS localhost:8080/ | grep -q 'href="/compose-to-k8s"' curl -fsS -F compose_yaml=$'services:\n app:\n image: nginx\n ports: ["80"]' \ localhost:8080/compose-to-k8s | grep -q 'kind: Deployment' + curl -fsS -F template=$'Resources:\n Logs:\n Type: AWS::S3::Bucket' \ + localhost:8080/cfn-to-terraform | grep -q 'aws_s3_bucket' - name: Show container logs if: failure() run: | @@ -114,6 +125,34 @@ jobs: - name: Validate manifests run: kubeconform -strict -summary -output pretty k8s/ + # Converts the CloudFormation fixtures and checks the Terraform with the real providers. + validate-terraform: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + cache: pip + cache-dependency-path: services/*/requirements-dev.txt + - name: Install converter-api dependencies + run: pip install -r services/converter-api/requirements.txt + - name: Install Terraform + run: | + curl -sSfL --retry 5 --retry-delay 5 --retry-all-errors -o terraform.zip \ + "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip" + echo "${TERRAFORM_SHA256} terraform.zip" | sha256sum -c - + unzip -q terraform.zip terraform + sudo mv terraform /usr/local/bin/ + terraform version + - name: terraform fmt and validate on every fixture + env: + # Each provider is downloaded once and shared by all fixtures. + TF_PLUGIN_CACHE_DIR: ${{ runner.temp }}/terraform-plugins + run: | + mkdir -p "$TF_PLUGIN_CACHE_DIR" + PYTHON=python scripts/validate-terraform.sh + # Deploys k8s/ to a real kind cluster (same config as `make cluster-up`) and uses the UI. # Catches what static checks can't: probes, securityContext vs the image, Pod Security, # and that the NetworkPolicy really blocks everything but web from reaching converter-api. @@ -167,6 +206,8 @@ jobs: # A conversion through the UI: web -> converter-api inside the cluster. curl -fsS -F compose_yaml=$'services:\n app:\n image: nginx\n ports: ["80"]' \ localhost:8080/compose-to-k8s | tee /tmp/convert.html | grep -q 'kind: Deployment' + curl -fsS -F template=$'Resources:\n Logs:\n Type: AWS::S3::Bucket' \ + localhost:8080/cfn-to-terraform | grep -q 'aws_s3_bucket' - name: converter-api is reachable from web only run: | # Single quotes only: this string is also embedded in the JSON below. The marker is @@ -219,7 +260,7 @@ jobs: # Only after every check above passes, and only for pushes to main (not PRs). publish: - needs: [lint, test, build, validate-k8s, e2e] + needs: [lint, test, build, validate-k8s, validate-terraform, e2e] if: github.event_name == 'push' && github.ref == 'refs/heads/main' permissions: contents: read diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9d290ad..9555706 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,56 +1,76 @@ # Contributing to DevToolkit -Thanks for helping. This guide covers local setup, adding a converter or service, and the PR process. +Thanks for helping. This guide covers local setup, the code rules, adding a converter or service and the PR process. ## Local setup ```bash make install # .venv with app + dev dependencies for every service -make lint # ruff check + format check, every service +make lint # ruff check + format check on every service, then the house code rules make test # pytest with coverage, every service make run # live-reloading API on http://localhost:8000 make run-web # live-reloading web UI on http://localhost:8080 (needs `make run` in another terminal) ``` -Install [kubeconform](https://github.com/yannh/kubeconform) if you change anything in `k8s/`, then run `make validate-k8s`. +Install [kubeconform](https://github.com/yannh/kubeconform) if you change anything in `k8s/`, then run `make validate-k8s`. Install [Terraform](https://developer.hashicorp.com/terraform/install) if you change the CloudFormation converter, then run `make validate-terraform`. + +## Code rules + +`make lint` and the `lint` CI job enforce these with ruff and `scripts/check_code_rules.py`. + +- **Functions live at module or class level.** A function or method never defines another one. Lambdas are replaced by named functions; pass a bound method as a callback. +- **No `*` or `**` syntax.** No star imports, `*args`, `**kwargs`, keyword-only markers or unpacking. Write `a + [b]`, `dict(a, key=value)` and explicit arguments. +- **Imports at the top of the module**, before any other statement. Never inside a function, a class, an `if` block or a test. +- **Problems get fixed at the cause.** Comments that switch a checker off (`noqa`, `type: ignore`, `pragma: no cover`, `nosec`) are not accepted. +- **Classes with one job each.** Dataclasses go in a `models.py` and constants in a `constants.py`. An `__init__.py` holds only a docstring or plain imports. +- **Docstrings and type hints** on every module, class, function and method outside `tests/`: what it does, plus an example when the input format needs one. +- **Comments explain why**, in plain words. +- **ruff** formats the code (`make format` fixes most things). + +## Writing rules + +For the docs, page copy and every message a user reads (errors, conversion notes): + +- Lead with the result, skip filler and prefer the smaller true claim. +- Say what something does or is. +- No apostrophes: write "does not" and "the stack name". +- No comma before "and" or "or". +- No em dashes. + +The Markdown checks run with the code rules. ## Adding a new converter -Example: adding a CloudFormation to Terraform converter. +Example: a Kubernetes to Docker Compose converter. + +1. **Logic.** Create a package `services/converter-api/converters/k8s_to_compose/`. Keep it pure: classes and functions take strings or dicts and return dicts, with no FastAPI imports, which keeps the logic easy to test. Give it a `models.py`, a `constants.py` and an `errors.py` with an error class that carries a message safe to show the user. +2. **Endpoint.** Add a route in `services/converter-api/main.py` with a Pydantic request model that sets a `max_length` on text fields. Return `{"success": true, ...}` on success and HTTP 400 with `{"success": false, "error": "..."}` for bad input. +3. **Tests.** Add tests covering the happy path, each supported input format and every error branch. CI fails under 95% coverage and the current code is at 100%. Please keep it there. +4. **Page.** Add a template in `services/web/templates/` and a router in `services/web/routes/`, following `routes/compose.py`: the form dataclass goes in `models.py`, its checks in `inputs.py`, the converter-api call in `conversions.py` and every user-facing text in `messages.py`. Include the router in `main.py`. Link it from `index.html` and `base.html`. Test it in `services/web/tests/` with the fake API from `conftest.py`. +5. **Docs.** Add the endpoint to `docs/reference/api.md` and its rules to a page in `docs/reference/`. Keep `README.md` to the overview and quick start. + +### CloudFormation to Terraform mappings -1. **Logic.** Create `services/converter-api/converters/cfn_to_terraform.py`. Keep it pure: functions take strings or dicts and return dicts. No FastAPI imports in here, which keeps the logic easy to test. - - A `parse_...()` function that validates input and raises a clear error. - - One or more `convert_...()` functions. -2. **Endpoint.** Add a route in `services/converter-api/main.py`. Use a Pydantic request model with a `max_length` on text fields. Return `{"success": true, ...}` on success and HTTP 400 with `{"success": false, "error": "..."}` for bad input. -3. **Tests.** Add `tests/test_cfn_to_terraform.py`, covering the happy path, each supported input format, and every error branch. CI fails under 95% coverage, and the current code is at 100%. Please keep it there. -4. **Page.** Add a template in `services/web/templates/` and a GET/POST route pair in `services/web/main.py`, following `compose_to_k8s.html`. Link it from `index.html` and `base.html`. Test it in `services/web/tests/` with the fake API from `conftest.py`. -5. **Docs.** Add the endpoint to `docs/reference/api.md` and its rules to `docs/reference/conversion-rules.md`. Keep `README.md` to the overview and quick start. +Each CloudFormation type with a hand-written `aws` provider mapping is a `ResourceConverter` subclass (`converters/cfn/resources/base.py`) in one of the modules in `converters/cfn/resources/`, listed in the `CONVERTERS` tuple of its module. The class names the two types and what `Ref` and `Fn::GetAtt` read. Its `convert(b)` method takes properties one at a time from `b.props` (`attr`, `number`, `json`, `tags`, `block`...). Properties it leaves are kept as comments and reported in the notes. Check attribute names against the provider schema (`terraform providers schema -json`), add the type to a fixture in `tests/fixtures/cfn/` and run `make validate-terraform`. Types without a mapping use the `awscc` provider through `converters/cfn/awscc_index.json`; rebuild that file with `python -m tools.build_awscc_index` (from `services/converter-api`) when you bump the awscc version. ## Adding a new service 1. `services//` with a `Dockerfile` that follows the existing ones: multi-stage, non-root UID 10001, `HEALTHCHECK`, `/health` and `/ready` endpoints. 2. `k8s//` manifests following the `web` pattern: probes, resource limits, non-root security context, a ConfigMap for its settings. The image name goes in `deployment.yaml`; scripts read it from there. -3. Add the name to the `SERVICES` list in `Makefile`, `.github/workflows/ci.yaml` and `scripts/deploy-local.sh`, add a job for it in `.github/workflows/build-push.yaml`, and its directory to `.github/dependabot.yml`. - -## Code style - -- **ruff** for linting and formatting (`make format` fixes most things). -- **Type hints** on all functions. -- **Docstrings** on public functions. Say what it does and give an example if the input format is non-obvious. -- **Comments explain why**, not what. Plain words, no buzzwords. +3. Add the name to the `SERVICES` list in `Makefile`, `.github/workflows/ci.yaml` and `scripts/deploy-local.sh`, add a job for it in `.github/workflows/build-push.yaml` and add its directory to `.github/dependabot.yml`. ## Web UI rules The design system is one file: `services/web/styles/input.css`. Every colour, size, radius and font is a token there, named for its job (`surface`, `ink`, `accent`), with light and dark values side by side. -- **No raw values in templates.** Use token classes (`bg-surface`, `text-ink-muted`, `border-hairline`, `rounded-sm`, `text-step-1`) and the component classes (`btn`, `card`, `field`, `alert`, `code`, `nav-link`). Tailwind's own palette, radii and text sizes are removed, so `bg-slate-50` or `rounded-lg` produce no CSS at all. If you need a value the tokens lack, add a token. -- **One component per concept.** A variant is a modifier class (`btn-primary`), not a new component. +- **Token classes in templates.** Use token classes (`bg-surface`, `text-ink-muted`, `border-hairline`, `rounded-sm`, `text-step-1`) and the component classes (`btn`, `card`, `field`, `alert`, `code`, `nav-link`). The Tailwind palette, radii and text sizes are removed, so `bg-slate-50` or `rounded-lg` produce no CSS at all. When you need a value the tokens lack, add a token. +- **One component per concept.** A variant is a modifier class (`btn-primary`). A part two pages share, such as the file list with tabs, is one template both include (`_files.html`). - **Both themes.** New colours get a light and a dark value, checked for contrast: 4.5:1 for text, 3:1 for interface borders. The two dark blocks in `input.css` must stay identical. -- **Keyboard and motion.** Anything clickable is at least 44px tall (`min-h-11`), focus stays visible, and animation respects `prefers-reduced-motion` (already handled globally). -- **Scripts.** `app.js` and the editor bundle are the only JavaScript, and every page must work without them: forms post and the server renders the result. The one inline script (theme before first paint) is allowed by hash in the Content-Security-Policy; don't add others. -- **Icons.** Inline SVGs from `templates/icons/` (`{% include "icons/copy.svg" %}`), sized by the `.icon` class. Add icons from the pinned Lucide release named in the docs, strip `width`/`height`, and add `aria-hidden="true"`. -- **Editors.** YAML goes through the CodeMirror editor (`services/web/editor/`), which reads its colours from the tokens. A new tool page needs only a `[data-editor]` container around its textarea and a result fragment; `app.js` does the rest. -- **Copy.** Lead with the result, no filler, no em dashes, and prefer the smaller true claim. The product is called DevToolkit; pages name what the tool does, not what to paste. +- **Keyboard and motion.** Anything clickable is at least 44px tall (`min-h-11`), focus stays visible and animation respects `prefers-reduced-motion` (handled globally). +- **Scripts.** `app.js` and the editor bundle are the only JavaScript. Every page works without them: forms post and the server renders the result. The one inline script (theme before first paint) is allowed by hash in the Content-Security-Policy; keep it the only one. +- **Icons.** Inline SVGs from `templates/icons/` (`{% include "icons/copy.svg" %}`), sized by the `.icon` class. Add icons from the pinned Lucide release named in the docs, strip `width`/`height` and add `aria-hidden="true"`. +- **Editors.** YAML and Terraform go through the CodeMirror editor (`services/web/editor/`), which reads its colours from the tokens. A new tool page needs only a `[data-editor]` container around its textarea and a result fragment; `app.js` does the rest. +- **Copy.** Follow the writing rules above. The product is called DevToolkit; pages name what the tool does. `make css` rebuilds `static/app.css` and `make editor` rebuilds `static/vendor/editor.js` (Node.js 22); the Dockerfile does both during the image build. @@ -62,16 +82,16 @@ Every container must have: - `livenessProbe` and `readinessProbe` - `runAsNonRoot: true`, `allowPrivilegeEscalation: false`, `capabilities.drop: ["ALL"]`, `readOnlyRootFilesystem: true` -The `devtoolkit` namespace enforces the `restricted` Pod Security Standard, so pods that break these rules are rejected by the cluster. +The `devtoolkit` namespace enforces the `restricted` Pod Security Standard, so the cluster rejects pods that break these rules. -**No secrets in code or manifests.** Use GitHub repo variables, Workload Identity, or Kubernetes Secrets created outside the repo. +**Secrets stay outside code and manifests.** Use GitHub repo variables, Workload Identity or Kubernetes Secrets created outside the repo. ## Pull request process 1. Branch from `main`. -2. Keep each PR to one change: one converter, one fix, and so on. +2. Keep each PR to one change: one converter, one fix and so on. 3. Run `make lint test` (and `make validate-k8s` if you touched `k8s/`) before pushing. -4. Open a PR into `main`. CI must pass: lint, tests, Docker builds, manifest validation, end-to-end on kind. +4. Open a PR into `main`. CI must pass: lint, tests, Docker builds, manifest validation, Terraform validation, end-to-end on kind. 5. A maintainer reviews and merges. Merging to `main` builds and pushes the images of the services that changed. ## License diff --git a/Makefile b/Makefile index d9c1e96..3b0e823 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ KIND_VERSION := $(shell awk '$$1 == "kind" {print $$2}' .tool-versions) TAILWIND_VERSION := $(shell sed -n -E 's/^ARG TAILWIND_VERSION=(.*)/\1/p' services/web/Dockerfile) .DEFAULT_GOAL := help -.PHONY: help install lint format test run run-web css editor build validate-k8s cluster-up cluster-down deploy-local port-forward clean +.PHONY: help install lint format test run run-web css editor build validate-k8s validate-terraform cluster-up cluster-down deploy-local port-forward clean help: ## List available commands @grep -E '^[a-zA-Z0-9_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-14s\033[0m %s\n", $$1, $$2}' @@ -17,8 +17,9 @@ $(VENV): install: $(VENV) ## Install dev dependencies for every service into .venv $(BIN)/pip install $(foreach s,$(SERVICES),-r services/$(s)/requirements-dev.txt) -lint: ## Run ruff lint and format checks on every service +lint: ## Run ruff and the house code rules (scripts/check_code_rules.py) on every service and the docs @for s in $(SERVICES); do echo "== $$s"; (cd services/$$s && ../../$(BIN)/ruff check . && ../../$(BIN)/ruff format --check .) || exit 1; done + @echo "== code rules"; $(BIN)/python scripts/check_code_rules.py format: ## Auto-format every service with ruff @for s in $(SERVICES); do (cd services/$$s && ../../$(BIN)/ruff check --fix . && ../../$(BIN)/ruff format .) || exit 1; done @@ -55,6 +56,9 @@ build: ## Build every service's Docker image validate-k8s: ## Validate K8s manifests with kubeconform kubeconform -strict -summary k8s/ +validate-terraform: ## Convert the CloudFormation fixtures and run terraform validate on them (needs terraform) + PYTHON=$(BIN)/python scripts/validate-terraform.sh + cluster-up: ## Create the local kind cluster (no-op if it exists) @kind version | grep -q '$(KIND_VERSION) ' \ || echo "warning: this project uses kind $(KIND_VERSION) (.tool-versions); you have: $$(kind version)" diff --git a/README.md b/README.md index 0bc3b06..947ca64 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,10 @@ Practical DevOps conversion tools, built as microservices on Kubernetes. DevToolkit has two jobs: -1. **Be useful.** Tools DevOps engineers reach for every day, starting with a Docker Compose to Kubernetes converter, usable from a web page or an API. -2. **Be a clean example.** Raw Kubernetes manifests (no Helm yet), health probes, resource limits, non-root containers, a NetworkPolicy and a full CI/CD pipeline, all small enough to read in one sitting. +1. **Be useful.** Two converters, each with a web page and an API: Docker Compose to Kubernetes, CloudFormation (with AWS SAM and AWS CDK) to Terraform. +2. **Be a clean example.** Plain Kubernetes manifests, health probes, resource limits, non-root containers, a NetworkPolicy and a full CI/CD pipeline, all small enough to read in one sitting. -It is two services: **web**, the pages you use in a browser, and **converter-api**, which does the conversions. Only web can reach the API. +It is two services: **web** serves the pages you use in a browser and **converter-api** does the conversions. Only web can reach the API. ## Quick start @@ -19,12 +19,13 @@ It is two services: **web**, the pages you use in a browser, and **converter-api |------|-----------------|------------| | [Python](https://www.python.org/) | 3.13 | Dev Mode | | [GNU Make](https://www.gnu.org/software/make/) | 3.81 | Dev Mode, Kubernetes Mode | -| [curl](https://curl.se/) | Any current release | Dev Mode (downloads the Tailwind CLI once, for the web UI's stylesheet) | -| [Node.js](https://nodejs.org/) | 22 | Dev Mode (bundles the web UI's code editor once, `make editor`) | +| [curl](https://curl.se/) | Any current release | Dev Mode (downloads the Tailwind CLI once, for the stylesheet of the web UI) | +| [Node.js](https://nodejs.org/) | 22 | Dev Mode (bundles the code editor of the web UI once, `make editor`) | | [Docker](https://docs.docker.com/get-docker/) | Any current release | Kubernetes Mode (builds the images; kind runs on it) | | [kind](https://kind.sigs.k8s.io/) | v0.33.0 (pinned in [`.tool-versions`](.tool-versions)) | Kubernetes Mode | | [kubectl](https://kubernetes.io/docs/tasks/tools/) | 1.36 (cluster runs Kubernetes 1.37) | Kubernetes Mode | | [jq](https://jqlang.org/) | 1.5 | Only the [example](#example) below | +| [Terraform](https://developer.hashicorp.com/terraform/install) | 1.5 | Only `make validate-terraform`, which checks the output of the CloudFormation converter | #### Dev Mode @@ -32,7 +33,7 @@ Runs both services directly with Python and reloads on every code change. ```bash make install # create .venv and install dependencies for every service -make test # run every service's tests with coverage +make test # run the tests of every service with coverage make run # start the API on http://localhost:8000 (docs at /docs) make run-web # in a second terminal: start the web UI on http://localhost:8080 ``` @@ -45,7 +46,7 @@ Builds both images and runs them on a local kind cluster, using the same manifes make deploy-local # create the kind cluster if needed, build the images, deploy k8s/ make port-forward # forward localhost:8080 to the web UI (keep it running) # then open http://localhost:8080 in your browser -make cluster-down # delete the cluster when you're done +make cluster-down # delete the cluster when you are done ``` #### All Commands @@ -82,12 +83,33 @@ kind: Service protocol: TCP ``` +A CloudFormation template works the same way, with `/convert/cfn-to-terraform`: + +```bash +curl -s localhost:8000/convert/cfn-to-terraform \ + -H 'Content-Type: application/json' \ + -d '{"template": "Resources:\n Logs:\n Type: AWS::S3::Bucket\n Properties:\n VersioningConfiguration:\n Status: Enabled"}' \ + | jq -r '.files[] | select(.path == "main.tf") | .content' +``` + +```hcl +resource "aws_s3_bucket" "logs" {} + +resource "aws_s3_bucket_versioning" "logs_versioning" { + bucket = aws_s3_bucket.logs.id + versioning_configuration { + status = "Enabled" + } +} +``` + ## Documentation | Topic | | |-------|-| | [API reference](docs/reference/api.md) | Endpoints, requests, responses, errors, input limits | | [Conversion rules](docs/reference/conversion-rules.md) | How each compose field maps to Kubernetes | +| [CloudFormation to Terraform](docs/reference/cloudformation-to-terraform.md) | How CloudFormation, SAM and CDK templates become Terraform | | [Architecture](docs/architecture.md) | Project layout, the two services, how they run on Kubernetes | | [CI/CD](docs/operations/ci-cd.md) | Workflows, image publishing, security scanning | | [Deploying to your cluster](docs/operations/deploy.md) | Run it on any Kubernetes cluster | diff --git a/SECURITY.md b/SECURITY.md index 04c6ebe..3ac96cc 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,9 +6,9 @@ Only the latest code on `main` (and the image tagged `latest`) gets security fix ## Reporting a vulnerability -**Please don't open a public issue for security problems.** +**Please report security problems privately.** -Report it privately through GitHub instead: go to the **Security** tab of this repository and click **Report a vulnerability**. Only the maintainers can see the report. +Report through GitHub: go to the **Security** tab of this repository and click **Report a vulnerability**. Only the maintainers can see the report. Please include: @@ -16,7 +16,7 @@ Please include: - steps or an input that reproduces it - what an attacker could do with it -You'll get an acknowledgement within 7 days. Once a fix is released we'll credit you in the advisory, unless you'd rather stay anonymous. +You get an acknowledgement within 7 days. Once a fix is released we credit you in the advisory; tell us if you prefer to stay anonymous. ## Scope @@ -29,4 +29,4 @@ In scope: Out of scope: - deployments run by other people with their own configuration -- denial of service by sending a very large number of requests (rate limiting is not part of this project) +- denial of service by sending a very large number of requests: this project leaves rate limiting to the platform it runs on diff --git a/docs/README.md b/docs/README.md index fd2ec95..29158cd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,10 +6,11 @@ Start with the [main README](../README.md) for the quick start. Everything else - [API reference](reference/api.md): endpoints, request and response formats, errors, input limits - [Conversion rules](reference/conversion-rules.md): how each docker-compose field maps to Kubernetes +- [CloudFormation to Terraform](reference/cloudformation-to-terraform.md): how CloudFormation, AWS SAM and AWS CDK templates become Terraform -## How it's built +## How it is built -- [Architecture](architecture.md): the two services, project layout, and how they run on Kubernetes +- [Architecture](architecture.md): the two services, project layout and how they run on Kubernetes ## Running it @@ -17,9 +18,9 @@ Start with the [main README](../README.md) for the quick start. Everything else - [Deploying to your cluster](operations/deploy.md): run it on any Kubernetes cluster - [Configuration](configuration.md): environment variables -## Where it's going +## Where it is going -- [Roadmap](roadmap.md): planned features in priority order, timeline, and what's out of scope +- [Roadmap](roadmap.md): planned features in priority order, timeline and what is out of scope ## Contributing diff --git a/docs/architecture.md b/docs/architecture.md index dfb9228..887a789 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,10 +4,10 @@ | Service | What it does | Port | Reachable from | |---------|--------------|------|----------------| -| `web` | Serves the pages (Docker Compose → Kubernetes, YAML validator). Calls `converter-api` from the server side. | 8080 | Users | +| `web` | Serves the pages (Docker Compose → Kubernetes, CloudFormation → Terraform, YAML validator). Calls `converter-api` from the server side. | 8080 | Users | | `converter-api` | The conversions, as a JSON API | 8000 | `web` only | -Browsers never talk to `converter-api`. In the cluster a [NetworkPolicy](../k8s/converter-api/networkpolicy.yaml) allows traffic to it only from `web` pods. This keeps one place (`web`) responsible for input handling and output pages, and lets the API change without breaking anyone who might have scripted against it. +Only `web` calls `converter-api`. In the cluster a [NetworkPolicy](../k8s/converter-api/networkpolicy.yaml) admits traffic to it from `web` pods alone. That keeps input handling and output pages in one place (`web`) and leaves the API free to change. ## Project layout @@ -15,21 +15,59 @@ Browsers never talk to `converter-api`. In the cluster a [NetworkPolicy](../k8s/ services/ converter-api/ FastAPI service: the conversions main.py HTTP endpoints - converters/ Conversion logic (pure functions, no FastAPI) - tests/ pytest tests + schemas.py Request bodies of the endpoints + converters/ Conversion logic, free of FastAPI + yaml_safety.py YAML loader with size, depth and alias limits + compose_to_k8s.py Docker Compose to Kubernetes + compose_constants.py Name limits, resource defaults, output kinds + render.py Manifests as files or as a Helm chart + cfn/ CloudFormation, SAM and CDK to Terraform + constants.py Limits, provider versions, accepted options + models.py HCL nodes and the facts about parameters and resources + errors.py CfnError + parse.py Template text to a checked dict + sam.py SAM expansion, one expander class per SAM resource type + sam_policies.py SAM policy templates as IAM statements + sam_constants.py SAM tables: globals, inherited attributes, function properties + cdk.py CDK clean-up: metadata, asset parameters, names + cdk_constants.py The CDK custom resources, metadata and bootstrap names it handles + expressions.py Intrinsic functions as HCL expressions + context.py Conversion state: names, variables, locals, notes + builder.py Props and Builder, the toolkit of a resource converter + resources/ Hand-written aws provider mappings: base.py (ResourceConverter), + registry.py and one module per AWS service group + awscc.py Any other type with the awscc provider, from awscc_index.json + convert.py Converter: the files of one template + pipeline.py TemplateConverter: text in, files and notes out + hcl.py HCL rendering that matches terraform fmt + tools/ Developer scripts, run as python -m tools.: build_awscc_index, + convert_fixtures and validate_report (for validate-terraform.sh) + tests/ pytest tests; fixtures/cfn/ holds the templates checked with Terraform Dockerfile Multi-stage build, non-root user - web/ FastAPI + Jinja2 service: the pages - main.py Routes, form handling, result fragments, zip download, security headers + web/ FastAPI and Jinja2 service: the pages + main.py create_app: wires routers, middleware and error handlers + routes/ One router per page: home, compose, cfn, yaml_check + conversions.py ConverterService: form to converter-api call to page context + inputs.py, models.py Form reading and checks, form and outcome dataclasses + settings.py Paths, limits, accepted options, environment variable names + messages.py Every user-facing text + examples.py The example inputs + security.py Security headers and cache rules + middleware.py Body size limit and headers on every response + rendering.py Jinja2 setup and page helpers + archives.py Zip downloads and the notes file + error_pages.py HTTP and form error pages api_client.py Calls converter-api (with a Google identity token on Cloud Run) - templates/ Jinja2 templates: index, the two tools, result fragments, error page + templates/ Jinja2 templates: index, one per tool, result fragments, error page. + _files.html is the file list both result fragments share icons/ Lucide icons (ISC) and the GitHub mark (Simple Icons, CC0), inlined - static/ app.js (editors, in-place results, theme, copy/download); - app.css and vendor/editor.js are built, not committed + static/ app.js (editors, in-place results, theme, copy and download); + the image build writes app.css and vendor/editor.js here styles/input.css The design system: every colour, size and radius as a token, light - and dark values, and the component classes. Compiled by Tailwind. - editor/ CodeMirror 6 YAML editor: src/editor.js plus pinned npm dependencies, - bundled by esbuild into static/vendor/editor.js - tests/ pytest tests; converter-api is replaced by a fake + and dark values and the component classes. Compiled by Tailwind. + editor/ CodeMirror 6 editor (YAML plus HCL for Terraform output): + src/editor.js plus pinned npm dependencies, bundled by esbuild + tests/ pytest tests; a fake stands in for converter-api Dockerfile Multi-stage build: Python deps, Tailwind CLI, Node (editor), runtime k8s/ namespace.yaml devtoolkit namespace @@ -38,17 +76,18 @@ k8s/ .github/ workflows/ CI, image publishing, CodeQL CODEOWNERS, dependabot.yml, issue and PR templates -scripts/ build.sh, deploy-local.sh, image-name.sh, kind-cluster.yaml +scripts/ build.sh, deploy-local.sh, image-name.sh, kind-cluster.yaml, + validate-terraform.sh, check_code_rules.py (the house rules) docs/ This documentation Makefile Common commands (`make help`) .tool-versions kind version (used by CI and checked by `make cluster-up`) ``` -Conversion logic lives in `converter-api/converters/` as plain functions that take strings or dicts and return dicts. `converter-api/main.py` only handles HTTP, and `web` only handles pages. This keeps the logic easy to test, and lets a future CLI reuse it. +Conversion logic lives in `converter-api/converters/` as classes and functions that take strings or dicts and return dicts. `converter-api/main.py` handles HTTP alone and `web` handles pages alone. That keeps the logic easy to test and ready for a future CLI. ## How it runs on Kubernetes -The manifests in `k8s/` are plain YAML, no Helm. Both services follow the same pattern: +The manifests in `k8s/` are plain YAML. Both services follow the same pattern: | Aspect | Setting | |--------|---------| @@ -57,23 +96,23 @@ The manifests in `k8s/` are plain YAML, no Helm. Both services follow the same p | Resources | `converter-api`: requests 100m CPU / 64Mi, limits 250m CPU / 128Mi. `web`: requests 100m CPU / 96Mi, limits 250m CPU / 192Mi | | User | UID/GID 10001, `runAsNonRoot` | | Filesystem | read-only root filesystem | -| Privileges | all Linux capabilities dropped, no privilege escalation, `RuntimeDefault` seccomp, no service account token mounted | +| Privileges | all Linux capabilities dropped, privilege escalation off, `RuntimeDefault` seccomp, service account token unmounted | | Config | a ConfigMap per service, see [Configuration](configuration.md) | -| Network | ClusterIP Services (`web` on 8080, `converter-api` on 8000), not reachable from the internet. `converter-api` accepts traffic from `web` pods only | +| Network | ClusterIP Services (`web` on 8080, `converter-api` on 8000), internal to the cluster. `converter-api` accepts traffic from `web` pods only | The `devtoolkit` namespace enforces the `restricted` [Pod Security Standard](https://kubernetes.io/docs/concepts/security/pod-security-standards/), so the cluster rejects any pod that tries to run as root. -`web`'s readiness probe does not check `converter-api`. If the API is down, the pages stay up and show an error instead, so one slow service can't take the other out of rotation. +The readiness probe of `web` checks `web` alone. When the API is down, the pages stay up and show an error, so each service stays in rotation on its own health. ## Images Both Dockerfiles use the official slim Python image (the exact version is set in each Dockerfile and kept current by Dependabot) and run as UID 10001. Each has a Docker `HEALTHCHECK` for plain `docker run`; Kubernetes uses its own probes instead. - `services/converter-api/Dockerfile`: **builder** installs dependencies into a virtualenv; **runtime** copies only the virtualenv and the code. -- `services/web/Dockerfile`: the same two stages, plus a **css** stage that downloads Tailwind's standalone CLI (version and SHA-256 pinned in the Dockerfile) and compiles `styles/input.css` into one small stylesheet, and an **editor** stage that bundles the CodeMirror editor from `editor/` with esbuild (`npm ci` against the committed lockfile). Neither tool reaches the runtime image. +- `services/web/Dockerfile`: the same two stages, plus a **css** stage that downloads the standalone Tailwind CLI (version and SHA-256 pinned in the Dockerfile) and compiles `styles/input.css` into one small stylesheet plus an **editor** stage that bundles the CodeMirror editor from `editor/` with esbuild (`npm ci` against the committed lockfile). The runtime image gets their output alone. ## How a page works -Every page works without JavaScript: the form posts, the server renders the whole page again with the result. With JavaScript, `app.js` posts the same form with an `X-Requested-With: fetch` header, the server returns only the result fragment (`_result.html` or `_validation.html`), and the script swaps it in place, turns the file list into tabs, mounts a read-only editor per file, and marks the error line in the input editor from the fragment's `data-error-line` attribute. The zip download is a plain form post to `/compose-to-k8s/zip`. +Every page works without JavaScript: the form posts and the server renders the whole page again with the result. With JavaScript, `app.js` posts the same form with an `X-Requested-With: fetch` header. The server then returns the result fragment alone (`_result.html`, `_terraform_result.html` or `_validation.html`) and the script swaps it in place, turns the file list into tabs, mounts a read-only editor per file and marks the error line in the input editor from the `data-error-line` attribute of the fragment. The zip downloads are plain form posts to `/compose-to-k8s/zip` and `/cfn-to-terraform/zip`. Images are published to GitHub Container Registry, one per service, tagged with the commit SHA and `latest`. Each image name is set once, in `k8s//deployment.yaml`; scripts and CI read it from there. See [CI/CD](operations/ci-cd.md). diff --git a/docs/configuration.md b/docs/configuration.md index 870ed62..820f63c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -6,7 +6,7 @@ Both services are configured with environment variables. | Variable | Default | Allowed values | What it does | |----------|---------|----------------|--------------| -| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, `error`, `critical` (any case) | How much the service logs. `info` logs rejected conversions; `debug` adds more detail. An unknown value doesn't stop the service: it logs a warning and uses `info`. | +| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, `error`, `critical` (any case) | How much the service logs. `info` logs rejected conversions; `debug` adds more detail. An unknown value makes the service log a warning and use `info`. | The service always listens on port **8000**. @@ -16,7 +16,7 @@ The service always listens on port **8000**. |----------|---------|----------------|--------------| | `LOG_LEVEL` | `info` | as above | As above. `error` logs each time `converter-api` could not be reached. | | `CONVERTER_API_URL` | `http://localhost:8000` | A URL | Where `converter-api` is. In the cluster: `http://converter-api:8000` (the Service name). | -| `CONVERTER_API_AUTH` | `none` | `none`, `google` | `google` sends a Google identity token with each API call, for a `converter-api` that requires authentication (Google Cloud Run). Needs the Google metadata server, so only works on Google Cloud. | +| `CONVERTER_API_AUTH` | `none` | `none`, `google` | `google` sends a Google identity token with each API call, for a `converter-api` that requires authentication (Google Cloud Run). Needs the Google metadata server, which exists on Google Cloud. | The service always listens on port **8080**. @@ -30,4 +30,4 @@ The service always listens on port **8080**. ## Fixed limits -Input limits (100,000 characters, nesting depth, value count) are fixed in code, not configurable. See [API reference: input limits](reference/api.md#input-limits). `web` checks the length first, so you get a readable message instead of an API error, and refuses request bodies larger than about 400 KB. +Input limits (characters, nesting depth, value count) are fixed in code. See [API reference: input limits](reference/api.md#input-limits). `web` checks the length first and shows a readable message on the page. It refuses request bodies larger than about 2 MB. diff --git a/docs/operations/ci-cd.md b/docs/operations/ci-cd.md index a849441..5038876 100644 --- a/docs/operations/ci-cd.md +++ b/docs/operations/ci-cd.md @@ -7,7 +7,7 @@ All automation runs in GitHub Actions, from `.github/workflows/`. | Workflow | Runs when | What it does | |----------|-----------|--------------| | `ci.yaml` | PR to `main`, push to `main` | Lint, tests, Docker builds, manifest validation, deploy to a real cluster (jobs below) | -| `build-push.yaml` | Called by CI on `main` after every check passes. Can also be run by hand. | Builds and pushes each service's image to GitHub Container Registry, if that service changed | +| `build-push.yaml` | Called by CI on `main` after every check passes. Can also be run by hand. | Builds and pushes the image of each changed service to GitHub Container Registry | | `codeql.yaml` | PR to `main`, push to `main`, weekly | Security scan of the Python code and the workflow files | ### CI jobs @@ -16,29 +16,31 @@ Every job covers both services. The list of services is one line at the top of ` | Job | Checks | |-----|--------| -| `lint` | `ruff check` and `ruff format --check` on each service | -| `test` | pytest on each service; fails if either is under **95%** coverage | -| `build` | Builds both Docker images, starts them on one Docker network, and runs a conversion through the web UI, so `web` → `converter-api` is proven to work | +| `lint` | `ruff check` and `ruff format --check` on each service, then `scripts/check_code_rules.py` on the whole repo: the code rules and writing rules in [CONTRIBUTING](../../CONTRIBUTING.md) | +| `test` | pytest on each service; fails when either is under **95%** coverage | +| `build` | Builds both Docker images, starts them on one Docker network and runs a conversion through the web UI, so `web` → `converter-api` is proven to work | | `validate-k8s` | [kubeconform](https://github.com/yannh/kubeconform) `-strict` on `k8s/` (the maintained successor to kubeval) | -| `e2e` | Creates a [kind](https://kind.sigs.k8s.io/) cluster from `scripts/kind-cluster.yaml` (the same one as `make cluster-up`), deploys `k8s/`, waits for both rollouts, then uses the UI through the `web` Service, including a conversion. Finally it checks the NetworkPolicy: a `web` pod can reach `converter-api`, and a pod without the `web` label cannot | +| `validate-terraform` | Converts each CloudFormation, SAM and CDK test template in `services/converter-api/tests/fixtures/cfn/` to Terraform, once with the `aws` provider and once with `awscc`, then runs `terraform fmt -check` and `terraform validate` on every result. Warnings fail it too. The Terraform version and its SHA-256 are pinned in `ci.yaml` | +| `e2e` | Creates a [kind](https://kind.sigs.k8s.io/) cluster from `scripts/kind-cluster.yaml` (the same one as `make cluster-up`), deploys `k8s/`, waits for both rollouts, then uses the UI through the `web` Service, including a conversion. Last it checks the NetworkPolicy: a `web` pod reaches `converter-api` and a pod without the `web` label does not | -PR runs that get superseded by a newer push are cancelled. Runs on `main` always finish, so every passing commit gets its images. +A newer push to a PR cancels the runs of the older one. Runs on `main` always finish, so every passing commit gets its images. ## Image publishing - **One image per service:** `ghcr.io/zainsohail88/devtoolkit/converter-api` and `.../web`. -- **Tags:** each image is tagged with its full commit SHA. `:latest` only moves if that commit is still the newest on `main`, so a slow CI run for an older commit can't overwrite a newer image. -- **Never broken:** a commit that fails any CI job never gets an image. -- **Only what changed:** a service's image is built only when its `services//` directory changed in that push. Commits that only touch docs or `k8s/` build nothing. +- **Tags:** each image is tagged with its full commit SHA. `:latest` moves only when that commit is still the newest on `main`, so a slow CI run for an older commit leaves a newer image in place. +- **Only passing commits:** a commit that fails any CI job gets no image. +- **Only what changed:** the image of a service is built only when `services//` changed in that push. Commits that touch only docs or `k8s/` build nothing. ## Supply-chain protection | What | How | |------|-----| -| Pinned actions | Every third-party action is pinned to a full commit SHA (with the version in a comment), so a moved or hijacked tag can't change what runs | +| Pinned actions | Every third-party action is pinned to a full commit SHA (with the version in a comment), so a moved or hijacked tag has no effect on what runs | | Pinned Tailwind CLI | The `web` Dockerfile downloads a fixed version and checks its SHA-256 before using it | -| Locked editor bundle | The code editor's npm dependencies are pinned exactly in `services/web/editor/package-lock.json` and installed with `npm ci`; the bundle is built in the image, never committed | -| Dependabot | Weekly update PRs for both services' Python packages and Docker base images, the editor's npm packages, and GitHub Actions. Minor and patch bumps are grouped; major bumps get their own PR. | -| CodeQL | `security-extended` queries on Python and on the workflows, e.g. to catch script injection | -| CODEOWNERS | `.github/` changes need the repo owner's review | +| Pinned Terraform | CI downloads a fixed Terraform release and checks its SHA-256 before using it | +| Locked editor bundle | The npm dependencies of the code editor are pinned exactly in `services/web/editor/package-lock.json` and installed with `npm ci`; the image builds the bundle | +| Dependabot | Weekly update PRs for the Python packages and Docker base images of both services, the npm packages of the editor and GitHub Actions. Minor and patch bumps are grouped; each major bump gets its own PR. | +| CodeQL | `security-extended` queries on Python and on the workflows, for example to catch script injection | +| CODEOWNERS | Changes to `.github/` need a review from the repo owner | | Least privilege | Workflows get read-only tokens by default and request `packages: write` or `id-token: write` only in the job that needs it | diff --git a/docs/operations/deploy.md b/docs/operations/deploy.md index 9903e60..d46bfb9 100644 --- a/docs/operations/deploy.md +++ b/docs/operations/deploy.md @@ -1,11 +1,11 @@ # Deploying to your own cluster -The manifests in `k8s/` work on any conformant Kubernetes cluster: a local one, GKE, EKS, AKS or self-hosted. Each published image is public, so no registry credentials are needed. +The manifests in `k8s/` work on any conformant Kubernetes cluster: a local one, GKE, EKS, AKS or self-hosted. Each published image is public, so pulling needs no registry credentials. ## Requirements - Kubernetes **1.25 or newer**. The `devtoolkit` namespace uses Pod Security admission, which is built in from 1.25. -- A CNI that enforces NetworkPolicy, if you want `converter-api` to be reachable from `web` only. kind's default (kindnet), Calico, Cilium and GKE Dataplane V2 do. Without one the policy is accepted but has no effect. +- A CNI that enforces NetworkPolicy, for `converter-api` to be reachable from `web` only. kindnet (the kind default), Calico, Cilium and GKE Dataplane V2 enforce it. On other CNIs the policy is accepted and has no effect. - `kubectl` pointed at the cluster you want, with permission to create a namespace. - Nodes able to pull from `ghcr.io`. diff --git a/docs/reference/api.md b/docs/reference/api.md index c43c8d0..e2679f9 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -12,7 +12,8 @@ The `web` service calls these endpoints from the server side. In the cluster, a | GET | `/ready` | Readiness probe: `{"status": "ready"}` | | POST | `/convert/compose-to-k8s` | Convert compose YAML, return manifests as JSON | | POST | `/convert/compose-to-k8s/yaml` | Same, return one multi-document YAML string | -| POST | `/convert/compose-to-k8s/files` | Same, return files: one per resource, or a Helm chart | +| POST | `/convert/compose-to-k8s/files` | Same, return files: one per resource or a Helm chart | +| POST | `/convert/cfn-to-terraform` | Convert a CloudFormation, AWS SAM or AWS CDK template to Terraform files | | POST | `/validate/yaml` | Check YAML syntax, report line/column of errors | ## Convert @@ -47,7 +48,7 @@ Both convert endpoints take the same request: `/convert/compose-to-k8s/yaml` returns `"yaml": "apiVersion: v1\n..."` in place of `manifests`: every resource in apply order (Namespace, PersistentVolumeClaims, Deployments, Services), separated by `---`. -`/convert/compose-to-k8s/files` takes one more field, `output`: `manifests` (default) or `helm`, and returns the result as files: +`/convert/compose-to-k8s/files` takes one more field, `output`: `manifests` (the default) or `helm`. It returns the result as files: ```json { @@ -65,6 +66,48 @@ With `output: helm` the files are `Chart.yaml`, `values.yaml` and `templates/*.y `notes` lists anything that needs a human decision. See [conversion rules](conversion-rules.md). +## CloudFormation to Terraform + +`POST /convert/cfn-to-terraform` converts a CloudFormation template (JSON or YAML), an AWS SAM template or the template `cdk synth` writes. See [CloudFormation to Terraform](cloudformation-to-terraform.md) for what becomes what. + +```json +{ + "template": "Resources:\n Bucket:\n Type: AWS::S3::Bucket\n", + "provider": "aws", + "layout": "files", + "stack_name": "shop", + "include_imports": false +} +``` + +| Field | Required | Default | Notes | +|-------|----------|---------|-------| +| `template` | yes | | The template as a string, at most 500,000 characters | +| `provider` | no | `aws` | `aws`: hand-written `aws` provider mappings, `awscc` for other types. `awscc`: every resource with `awscc` | +| `layout` | no | `files` | `files`: `versions.tf`, `variables.tf`, `locals.tf`, `main.tf`, `outputs.tf`. `single`: everything in `main.tf` | +| `stack_name` | no | | Default for `var.stack_name`, which replaces `AWS::StackName`. A letter, then letters, digits and `-` | +| `include_imports` | no | `false` | Also write `imports.tf`, to adopt the resources an existing stack created | + +**Success** (HTTP 200): + +```json +{ + "success": true, + "source": "cloudformation", + "files": [ + {"path": "versions.tf", "content": "terraform {\n..."}, + {"path": "main.tf", "content": "resource \"aws_s3_bucket\" \"bucket\" {}\n"} + ], + "notes": [], + "resources": [ + {"logical_id": "Bucket", "type": "AWS::S3::Bucket", "address": "aws_s3_bucket.bucket", "status": "aws"} + ], + "summary": {"resources": 1, "aws": 1, "awscc": 0, "unsupported": 0} +} +``` + +`source` is `cloudformation`, `sam` or `cdk`. `resources` lists each resource of the template (after SAM expansion) with its Terraform address; a resource left as a comment has address `null` and status `unsupported`. Errors use the same shape as the other endpoints, with `line` and `column` for syntax errors. A template with a structure the converter is unable to handle gets a 400 asking for an issue. + ## Validate `POST /validate/yaml` takes `{"yaml": "..."}`. Multi-document input (separated by `---`) is supported. @@ -81,15 +124,17 @@ With `output: helm` the files are `Chart.yaml`, `values.yaml` and `templates/*.y | Status | When | Body | |--------|------|------| -| 400 | The compose input can't be converted: invalid YAML, no services, a wrong field type, a bad value | `{"success": false, "error": "..."}` | -| 422 | The request itself is malformed: missing field, bad namespace name, input too long | FastAPI's standard validation error | +| 400 | The input is unconvertible: invalid YAML or JSON, no services or resources, a wrong field type, a bad value | `{"success": false, "error": "..."}` | +| 422 | The request itself is malformed: missing field, bad namespace or stack name, unknown option, input too long | The standard FastAPI validation error | ## Input limits -Real compose files are far below these limits. They exist so a hostile input can't tie up the server. +Real files are far below these limits. They cap the CPU time and memory a single request can use. + +| Limit | Compose and YAML check | CloudFormation | Response | +|-------|------------------------|----------------|----------| +| Input length | 100,000 characters | 500,000 characters | 422 | +| Nesting depth | 100 levels | 100 levels | 400 (`valid: false` from `/validate/yaml`) | +| Values in the document | 10,000 | 100,000 | 400 (`valid: false` from `/validate/yaml`) | -| Limit | Value | Response | -|-------|-------|----------| -| Input length | 100,000 characters | 422 | -| Nesting depth | 100 levels | 400 (`valid: false` from `/validate/yaml`) | -| Values in the document | 10,000, counted both as written and after expanding YAML anchors/aliases | 400 (`valid: false` from `/validate/yaml`) | +Values are counted both as written and after expanding YAML anchors and aliases. diff --git a/docs/reference/cloudformation-to-terraform.md b/docs/reference/cloudformation-to-terraform.md new file mode 100644 index 0000000..7fb3bfe --- /dev/null +++ b/docs/reference/cloudformation-to-terraform.md @@ -0,0 +1,173 @@ +# CloudFormation to Terraform + +How a CloudFormation, AWS SAM or AWS CDK template becomes Terraform. The [API reference](api.md#cloudformation-to-terraform) describes the endpoint. + +The rule is the same as for the other converters: whatever converts only in part is kept in the output as a comment and listed in `notes`. + +## Inputs + +| Input | How it is detected | What happens first | +|-------|--------------------|--------------------| +| CloudFormation, JSON or YAML | The default | Nothing | +| AWS SAM | `Transform: AWS::Serverless-2016-10-31` | `AWS::Serverless::*` resources expand into the resources SAM itself creates (see [SAM](#aws-sam)) | +| AWS CDK | An `AWS::CDK::Metadata` resource or `aws:cdk:path` metadata | CDK bookkeeping is removed and names come from construct paths (see [CDK](#aws-cdk)) | + +For a CDK app, run `cdk synth` and convert the template it writes to `cdk.out/.template.json`. + +Logical IDs and the names of parameters, conditions, mappings and outputs must be letters and digits, as CloudFormation requires. This also keeps every name safe to use in Terraform. `!Cidr` makes at most 256 blocks, as in CloudFormation. + +YAML short forms (`!Ref`, `!GetAtt A.B`, `!Sub`, `!If`...) are read as their long forms. Scalars are read the way CloudFormation reads them: `2010-09-09` stays a string and `0755` stays `"0755"`. + +## Output files + +| File | Holds | +|------|-------| +| `versions.tf` | `required_version` (Terraform 1.5 or later), the providers used (`aws ~> 6.40`, `awscc ~> 1.0`, `archive ~> 2.0`), empty provider blocks | +| `variables.tf` | One variable per parameter, plus `stack_name` and any placeholder variables | +| `locals.tf` | Mappings and conditions | +| `main.tf` | Data sources and resources, in template order | +| `outputs.tf` | One output per template output | +| `imports.tf` | With `include_imports`: an `import` block per resource | + +`layout: single` puts everything in `main.tf`. The output is formatted the way `terraform fmt` formats it. + +The providers take their region and credentials from the environment (`AWS_REGION`, `AWS_PROFILE`) like the AWS CLI, the same way a stack gets its region when it is deployed. + +## Providers + +With `provider: aws` (the default), the [85 types below](#hand-written-mappings) use hand-written mappings to the `aws` provider, which give the Terraform an experienced user writes: the versioning of an S3 bucket becomes `aws_s3_bucket_versioning`, IAM inline policies become `aws_iam_role_policy` and so on. + +Every other type uses the [`awscc` provider](https://registry.terraform.io/providers/hashicorp/awscc/latest/docs). awscc is generated from the CloudFormation resource schemas, so its resources match CloudFormation one to one: `AWS::Batch::JobQueue` becomes `awscc_batch_job_queue` and property `ComputeEnvironmentOrder` becomes `compute_environment_order`. DevToolkit ships an index of the 1,713 types awscc supports, built from the provider schema. The index gives the exact resource and attribute names, the properties that are maps (their keys stay as written) and the properties that are JSON documents (written with `jsonencode`). A property missing from the installed awscc version is listed in the notes. Each awscc type in use gets a note. + +With `provider: awscc`, every resource uses awscc. + +A type outside both (custom resources, `AWS::CloudFormation::*`, the few types awscc lacks) is written as a comment with its properties and listed in the notes. + +## Parameters + +| CloudFormation | Terraform | +|----------------|-----------| +| `Type: String`, `AWS::EC2::VPC::Id` and other AWS-specific types | `type = string` | +| `Type: Number` | `type = number`, default converted to a number | +| `List` | `list(number)` | +| `CommaDelimitedList`, `List` | `list(string)`, default `"a,b"` becomes `["a", "b"]` | +| `AWS::SSM::Parameter::Value<...>` | A variable holding the parameter name and a `data "aws_ssm_parameter"`; references read its value | +| `Description` (or the label from `AWS::CloudFormation::Interface`) | `description` | +| `NoEcho: true` | `sensitive = true`; outputs that use it are sensitive too | +| `AllowedValues` | `validation { condition = contains([...], var.x) }` | +| `AllowedPattern` | `validation { condition = can(regex("^(?:pattern)$", var.x)) }` | +| `MinLength` / `MaxLength`, `MinValue` / `MaxValue` | `validation` with `length()` or a comparison | +| `ConstraintDescription` | `error_message` | + +A parameter with a name Terraform reserves (`count`, `version`, `source`...) gets a trailing `_`. + +## References and functions + +| CloudFormation | Terraform | +|----------------|-----------| +| `!Ref Parameter` | `var.parameter` | +| `!Ref Resource` | The attribute the mapping says `Ref` returns: `aws_s3_bucket.x.id`, `aws_sqs_queue.x.url`, `aws_sns_topic.x.arn`... For awscc, `id` | +| `!GetAtt Resource.Attribute` | The mapped attribute (`Arn` → `arn`, `RepositoryUri` → `repository_url`); for other attributes the name in snake_case, with a note for aws types | +| `AWS::Region`, `AWS::AccountId`, `AWS::Partition`, `AWS::URLSuffix` | `data.aws_region.current.region`, `data.aws_caller_identity.current.account_id`, `data.aws_partition.current.partition` / `.dns_suffix` | +| `AWS::StackName` | `var.stack_name` (default: the `stack_name` option) | +| `AWS::NoValue` | `null` or the attribute is left out | +| `!Sub "a-${X}-${Y.Arn}"` | `"a-${var.x}-${aws_y.y.arn}"`, with `${!Literal}` kept as `$${Literal}` | +| `!Join`, `!Select`, `!Split` | A template string where it reads better, else `join()`, `element()`, `split()`; literal values are worked out in place | +| `!If [Cond, A, B]` | `local.cond ? A : B` | +| `!Equals`, `!And`, `!Or`, `!Not` | `==`, `&&`, `\|\|`, `!`. CloudFormation compares text, so literals become strings and a `Number` parameter goes through `tostring()` | +| `!FindInMap [Map, A, B]` | `local.map[A][B]`; with a `DefaultValue`, nested `lookup()` | +| `!GetAZs` | `data.aws_availability_zones.available.names` | +| `!Base64 x` | `base64encode(x)` | +| `!Cidr [block, count, bits]` | The list itself for a literal block, else a `for` expression over `cidrsubnet()` | +| `!ImportValue name` | A variable `import_`, with a note: stack exports exist in CloudFormation only | +| `Fn::ToJsonString`, `Fn::Length` (`AWS::LanguageExtensions`) | `jsonencode()`, `length()` | +| Policy documents, event patterns, state machine definitions | `jsonencode({...})` with the original keys | + +A reference to a resource that was left as a comment becomes a placeholder variable describing what it stands for, so the configuration still validates. + +`AWS::NoValue` is removed the way CloudFormation removes it: from a list (`[for item in [...] : item if item != null]`), from a mapping (`merge({...}, cond ? {key = value} : {})`) and from a `!Join`. A list item such as a policy ARN, a queue or a security group rule written as `!If [Cond, x, !Ref AWS::NoValue]` becomes a resource with `count = local.cond ? 1 : 0`. Inside JSON documents, an `!If` with branches of different shapes (a string or a list) is encoded per branch. + +### Known limitations + +- An `!If` that picks between two whole lists of nested blocks (for example two different `BlockDeviceMappings` lists) stays a comment and is listed in the notes. +- In ECS container definitions, a `!Ref` to a `Number` parameter used as an environment value stays a number; ECS expects a string there. + +## Resource attributes + +| CloudFormation | Terraform | +|----------------|-----------| +| `Condition` | `count = local.cond ? 1 : 0`; references to it use `[0]` | +| `DependsOn` | `depends_on` | +| `DeletionPolicy: Retain` | `lifecycle { prevent_destroy = true }`, with a note: Terraform then refuses to destroy the resource, where CloudFormation leaves it behind | +| `DeletionPolicy: Snapshot` | For RDS, `skip_final_snapshot = false` and a `final_snapshot_identifier` (also the default for DB instances, as in CloudFormation); for other types a note | +| `UpdateReplacePolicy`, `CreationPolicy`, `UpdatePolicy`, `AWS::CloudFormation::Init` | Notes | + +Where CloudFormation generates a name Terraform requires (a DynamoDB table, a Lambda function, an ECR repository...), the name becomes `${var.stack_name}-`, with a note. To adopt an existing resource, use its current name. + +## Hand-written mappings + +| Area | CloudFormation types | +|------|----------------------| +| S3 | `Bucket` (versioning, encryption, public access block, ownership controls, ACL, lifecycle, CORS, website, logging, acceleration, object lock and notifications each become their own resource), `BucketPolicy` | +| DynamoDB, ECR | `Table`, `Repository` (lifecycle and repository policies become their own resources) | +| IAM | `Role`, `Policy`, `ManagedPolicy`, `InstanceProfile`, `User`, `Group`. Inline policies and managed policy attachments become one resource each | +| Lambda | `Function`, `Permission`, `EventSourceMapping`, `LayerVersion`, `Url`, `Alias`, `Version` | +| EC2 compute, ECS | `Instance`, `LaunchTemplate`; `Cluster`, `TaskDefinition` (container definitions as ECS JSON), `Service` | +| API Gateway | `RestApi`, `Deployment`, `Stage`, `Resource`, `Method`; v2 `Api`, `Integration`, `Route`, `Stage`, `Authorizer` | +| Messaging | SQS `Queue`, `QueuePolicy`; SNS `Topic`, `Subscription`, `TopicPolicy`; EventBridge `Rule` (one target resource per target), `EventBus`; Kinesis `Stream`; Step Functions `StateMachine` | +| Networking | `VPC`, `Subnet`, `InternetGateway`, `EgressOnlyInternetGateway`, `VPCGatewayAttachment`, `RouteTable`, `Route`, `SubnetRouteTableAssociation`, `EIP`, `EIPAssociation`, `NatGateway`, `VPCEndpoint`, `SecurityGroup`, `SecurityGroupIngress`, `SecurityGroupEgress`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` | +| Load balancing, DNS, certificates, CDN | ELBv2 `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerCertificate`, `ListenerRule`; Route 53 `HostedZone`, `RecordSet`, `RecordSetGroup`; ACM `Certificate` (DNS validation records and `aws_acm_certificate_validation` when the zone is known); CloudFront `Distribution`, `OriginAccessControl`, `CloudFrontOriginAccessIdentity` | +| Databases, secrets, keys | RDS `DBInstance`, `DBCluster`, `DBSubnetGroup`, `DBParameterGroup`; KMS `Key`, `Alias`; Secrets Manager `Secret`; SSM `Parameter` | +| Observability | Logs `LogGroup`, `MetricFilter`, `SubscriptionFilter`; CloudWatch `Alarm`, `Dashboard` | + +These differences between CloudFormation and Terraform are handled for you: + +- A security group without egress rules gets the implicit allow-all egress rule of CloudFormation written out, because `aws_security_group` removes it. +- Lambda `ZipFile` code becomes an `archive_file` data source, named after the handler and runtime (`index.py`, `index.js`). +- `AWS::Lambda::Version` becomes `publish = true` on the function plus a `terraform_data` that records the version; in the aws provider, versions belong to the function. +- An API Gateway deployment is redeployed when the API body changes and keeps `create_before_destroy`. + +A property a mapping leaves out is written as a comment in the resource and listed in the notes. + +## AWS SAM + +SAM resources expand with the logical IDs SAM uses, so references in the template (`!GetAtt MyFunctionRole.Arn`, `!Ref ServerlessRestApi`, `!Ref MyFunction.Alias`) keep working. + +| SAM | Becomes | +|-----|---------| +| `Globals` | Merged into each resource the way SAM merges them: the value on the resource wins, maps merge, lists add up | +| `AWS::Serverless::Function` | A function and its role `Role` with `AWSLambdaBasicExecutionRole` (plus X-Ray for `Tracing: Active` and VPC access for `VpcConfig`) | +| `CodeUri: ./src` | An `archive_file` that zips the folder; `s3://` URIs and `{Bucket, Key}` become S3 code | +| `InlineCode`, `ImageUri` | `ZipFile` code, an image function | +| `Policies` | Managed policy names, policy documents and the common [policy templates](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-template-list.html) (DynamoDB, S3, SQS, SNS, Lambda, Step Functions, EventBridge, SSM, Secrets Manager, KMS, Kinesis, CloudWatch, VPC access...). Other templates are listed in the notes | +| Events: `Api`, `HttpApi` | Paths in the generated OpenAPI body of `ServerlessRestApi` / `ServerlessHttpApi` (or your `AWS::Serverless::Api`) and a Lambda permission | +| Events: `SQS`, `Kinesis`, `DynamoDB` | An event source mapping and the matching managed policy | +| Events: `Schedule`, `EventBridgeRule`, `CloudWatchEvent`, `ScheduleV2` | An EventBridge rule (or an EventBridge Scheduler schedule and its role) and a permission | +| Events: `SNS`, `S3`, `CloudWatchLogs` | A subscription, a notification on the bucket or a subscription filter, plus a permission | +| `AutoPublishAlias`, `FunctionUrlConfig`, `DeadLetterQueue` | A version and an alias that the events point at, a function URL, a dead-letter target and its permission | +| `AWS::Serverless::Api`, `HttpApi` | API, deployment and stage. `DefinitionUri: api.yaml` becomes `yamldecode(file("api.yaml"))` | +| `AWS::Serverless::SimpleTable`, `LayerVersion`, `StateMachine` | A table (on-demand unless throughput is given), a layer version, a state machine with its role, events and `DefinitionSubstitutions` applied | +| `AWS::Serverless::Connector` and `Connectors` | IAM policies on the role of the source; Lambda permissions for API, SNS, S3 and EventBridge sources | + +`DeploymentPreference`, `Auth`, `Cors` (on REST APIs), `Domain`, `AWS::Serverless::Application` and other settings without an equivalent are listed in the notes. + +## AWS CDK + +- `CDKMetadata`, the `BootstrapVersion` parameter and the `CheckBootstrapVersion` rule are left out. +- Terraform names come from construct paths: `MyStack/Api/Handler/Resource` becomes `api_handler`. +- Lambda and layer code from assets is read from `cdk.out/asset.` and zipped with `archive_file`. Keep `cdk.out` next to the Terraform files. +- `autoDeleteObjects` becomes `force_destroy = true` on the bucket; the helper function of the CDK, its role and its bucket policy statement are left out. +- `logRetention` becomes an `aws_cloudwatch_log_group` with that retention. +- `restrictDefaultSecurityGroup` becomes a note to add an `aws_default_security_group`. + +## Moving a stack to Terraform + +With `include_imports`, `imports.tf` has an [`import` block](https://developer.hashicorp.com/terraform/language/import) per resource, so Terraform adopts what the stack created. Where the template gives the name of a resource as a literal, the import ID is that name; elsewhere it is `TODO`, to be replaced with the physical ID from `aws cloudformation describe-stack-resources --stack-name `. Then: + +1. Set `DeletionPolicy: Retain` on every resource and update the stack. +2. Run `terraform plan` until it shows no changes. +3. Delete the stack. The resources stay, now managed by Terraform. + +## Checking the output + +`make validate-terraform` converts each CloudFormation, SAM and CDK test template in `services/converter-api/tests/fixtures/cfn/` twice, once for each provider. It runs `terraform fmt -check` and `terraform validate` on every result and fails on errors and warnings. CI runs it on every pull request. diff --git a/docs/reference/conversion-rules.md b/docs/reference/conversion-rules.md index 46ad6a0..212b911 100644 --- a/docs/reference/conversion-rules.md +++ b/docs/reference/conversion-rules.md @@ -1,6 +1,6 @@ # Conversion rules -How each docker-compose (v3) field becomes Kubernetes. The output is proportional to the input: only the resources the compose file needs are generated, nothing else. +How each docker-compose (v3) field becomes Kubernetes. The output is proportional to the input: exactly the resources the compose file needs. ## What is generated @@ -8,8 +8,8 @@ How each docker-compose (v3) field becomes Kubernetes. The output is proportiona |---------|------------|------| | `services.` | Deployment | Always | | `services..ports` / `expose` | ClusterIP Service | The service has ports and Services are enabled | -| Named volume (`dbdata:/var/lib/postgresql/data`) | PersistentVolumeClaim, one per volume name | The volume is not `external` | -| `namespace` other than `default` | Namespace | Requested namespace is not `default` | +| Named volume (`dbdata:/var/lib/postgresql/data`) | PersistentVolumeClaim, one per volume name | The volume is internal (`external` unset) | +| `namespace` other than `default` | Namespace | The requested namespace is another one | Files are written in apply order: Namespace, PersistentVolumeClaims, Deployments, Services. @@ -26,7 +26,7 @@ Files are written in apply order: Namespace, PersistentVolumeClaims, Deployments | `deploy.resources.limits` | `resources.limits` | | `deploy.resources.reservations` | `resources.requests` | | `healthcheck` | `livenessProbe` and `readinessProbe` | -| `depends_on` | `initContainers` that wait for the dependency's port | +| `depends_on` | `initContainers` that wait for the port of the dependency | | `volumes` | `volumes` + `volumeMounts`, PersistentVolumeClaims for named volumes | ### Ports @@ -39,7 +39,7 @@ Files are written in apply order: Namespace, PersistentVolumeClaims, Deployments | `"53:53/udp"` | 53/UDP | 53/UDP | | `{target: 80, published: 8080}` | 8080 | 80 | -Port ranges (`"3000-3005"`) aren't supported and return an error. +Port ranges (`"3000-3005"`) return an error. ### Resources @@ -85,7 +85,7 @@ initContainers: command: [sh, -c, "until nc -z db 5432; do sleep 2; done"] ``` -A dependency without ports (or with Services disabled) can't be waited on, so it is reported as a note instead. A dependency that isn't a service in the file is an error. +A dependency without ports (or with Services disabled) has nothing to wait on, so it becomes a note. A dependency missing from the services of the file is an error. ### Volumes @@ -102,11 +102,11 @@ The PVC size is a placeholder and is reported as a note. A named volume mounted ## Notes for manual attention -Only what the conversion could not do for you is reported in `notes`: +`notes` lists what needs you: | Compose | Note | |---------|------| -| Bind mount | Kubernetes has no host paths; use a ConfigMap, bake it into the image, or a PVC | +| Bind mount | Kubernetes has no host paths; use a ConfigMap, bake it into the image or use a PVC | | `depends_on` a service without ports | Nothing to wait for; make the dependent retry its connection | | `networks` | Not needed in Kubernetes; services reach each other by name | | `env_file` | Move the values into a ConfigMap or Secret | @@ -118,11 +118,11 @@ Only what the conversion could not do for you is reported in `notes`: ## Helm chart -With `output: helm`, the same resources are written as a chart: `Chart.yaml`, a `values.yaml` holding what changes between environments (image, replicas, resources per service; size per volume), and one template per resource. Templates carry no namespace; Helm supplies the release namespace. The chart name comes from the compose file's top-level `name`, or `app`. +With `output: helm`, the same resources are written as a chart: `Chart.yaml`, a `values.yaml` holding what changes between environments (image, replicas, resources per service; size per volume) and one template per resource. Templates carry no namespace; Helm supplies the release namespace. The chart name comes from the top-level `name` of the compose file, with `app` as the fallback. ## Names -Kubernetes names must be lowercase letters, digits and `-`, start with a letter, and be at most 63 characters. Invalid names are fixed and noted: +Kubernetes names must be lowercase letters, digits and `-`, start with a letter and be at most 63 characters. Invalid names are fixed and noted: - `my_app` becomes `my-app` - `1api` becomes `svc-1api` @@ -131,7 +131,7 @@ If two services end up with the same name, conversion fails with an error. ## YAML parsing -Values are read the way Docker Compose reads them (YAML 1.2), not the older YAML 1.1 rules: +Values are read the way Docker Compose reads them, with YAML 1.2 rules: | Compose | YAML 1.1 would give | DevToolkit gives | |---------|---------------------|------------------| diff --git a/docs/roadmap.md b/docs/roadmap.md index bfe25cb..752fcd1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,8 +1,8 @@ # Roadmap -DevToolkit focuses on converters that are **rare or don't exist yet**. Tools that already exist in many places (Base64, JWT decoders, cron explainers and the like) are deliberately left out. +DevToolkit builds converters that are **rare or missing elsewhere**. Tools found in many places already (Base64, JWT decoders, cron explainers and the like) are left to those places. -Features are listed in priority order and tracked on the [DevToolkit roadmap board](https://github.com/users/zainsohail88/projects/2/views/3). Dates are targets, not promises. +Features are listed in priority order and tracked on the [DevToolkit roadmap board](https://github.com/users/zainsohail88/projects/2/views/3). Dates are targets. ## Timeline @@ -13,55 +13,54 @@ gantt axisFormat %b %Y section Q1 2027 - AWS to Terraform :t1, 2027-01-01, 2027-02-14 - Two-way CI converter :t2, 2027-02-15, 2027-03-31 + Two-way CI converter :t1, 2027-02-15, 2027-03-31 section Q2 2027 - K8s to Compose :t3, 2027-04-01, 2027-05-15 + K8s to Compose :t2, 2027-04-01, 2027-05-15 section Q3 2027 - Compose/K8s with ECS :t4, 2027-07-01, 2027-08-15 - nginx.conf to Gateway API :t5, 2027-08-16, 2027-09-30 + Compose/K8s with ECS :t3, 2027-07-01, 2027-08-15 + nginx.conf to Gateway API :t4, 2027-08-16, 2027-09-30 section Q4 2027 - Firewall rules translator :t6, 2027-10-01, 2027-11-15 - Prometheus alerts :t7, 2027-11-16, 2027-12-31 + Firewall rules translator :t5, 2027-10-01, 2027-11-15 + Prometheus alerts :t6, 2027-11-16, 2027-12-31 ``` ## Planned -| # | Feature | What it does | Why it's needed | -|---|---------|--------------|-----------------| -| 1 | **AWS → Terraform** | CloudFormation (JSON/YAML), AWS SAM and AWS CDK (via `cdk synth` output) → Terraform | Only one CloudFormation converter exists, and none for CDK | -| 2 | **Two-way CI converter** | Any direction between GitHub Actions, GitLab CI, CircleCI, Jenkins (declarative) and Azure Pipelines | Existing tools convert one way only, into GitHub Actions | -| 3 | **Kubernetes → Docker Compose** | Deployments, Services, ConfigMaps → Compose services | No maintained tool goes this direction | -| 4 | **Compose / Kubernetes ↔ AWS ECS** | Both directions between Compose, Kubernetes and ECS task definitions | Existing tools are stale or only partly cover Compose | -| 5 | **nginx.conf → Gateway API** | `server`/`location`/`proxy_pass` → `Gateway` + `HTTPRoute` | Existing tools start from Kubernetes Ingress, not raw nginx config | -| 6 | **Firewall rules translator** | Any direction between AWS Security Groups, GCP firewall rules, Azure NSGs and Kubernetes NetworkPolicy | No tool covers GCP or NetworkPolicy | -| 7 | **Prometheus alerts → Datadog / CloudWatch** | Prometheus alerting rules → Datadog monitors and CloudWatch alarms | No converter targets Datadog or CloudWatch | +| Feature | What it does | Why it is needed | +|---------|--------------|------------------| +| **Two-way CI converter** | Any direction between GitHub Actions, GitLab CI, CircleCI, Jenkins (declarative) and Azure Pipelines | Existing tools convert one way only, into GitHub Actions | +| **Kubernetes → Docker Compose** | Deployments, Services, ConfigMaps → Compose services | No maintained tool goes this direction | +| **Compose / Kubernetes ↔ AWS ECS** | Both directions between Compose, Kubernetes and ECS task definitions | Existing tools are stale or cover Compose in part | +| **nginx.conf → Gateway API** | `server`/`location`/`proxy_pass` → `Gateway` + `HTTPRoute` | Existing tools start from Kubernetes Ingress | +| **Firewall rules translator** | Any direction between AWS Security Groups, GCP firewall rules, Azure NSGs and Kubernetes NetworkPolicy | No tool covers GCP or NetworkPolicy | +| **Prometheus alerts → Datadog / CloudWatch** | Prometheus alerting rules → Datadog monitors and CloudWatch alarms | No converter targets Datadog or CloudWatch | -Every converter follows the same rule as the existing one: anything it can't convert exactly is reported in `notes`, never silently dropped or guessed. Each one gets a page in the web UI as well as an API endpoint. +Every converter follows the same rule as the existing ones: whatever it converts only in part is reported in `notes`. Each one gets a page in the web UI as well as an API endpoint. -## Not yet scheduled +## Later - Ad-supported public hosting, from the original project vision. Revisit once the web UI has been live for a while. ## Done - `converter-api` (FastAPI): Docker Compose to Kubernetes, YAML validation +- **AWS → Terraform** ([#9](https://github.com/zainsohail88/devtoolkit/issues/9)): CloudFormation (JSON/YAML), AWS SAM and AWS CDK (`cdk synth` output) to Terraform, with hand-written `aws` provider mappings for 85 common types and the `awscc` provider for the rest; CI checks the output with `terraform validate`. See [CloudFormation to Terraform](reference/cloudformation-to-terraform.md) - `web` (FastAPI + Jinja2 + Tailwind): a page per tool, calls the API server-side; the API is reachable from `web` only -- Raw Kubernetes manifests: probes, resource limits, non-root, restricted Pod Security, NetworkPolicy -- CI: lint, tests with a 95% coverage gate, Docker builds, manifest validation, end-to-end on kind including the NetworkPolicy +- Plain Kubernetes manifests: probes, resource limits, non-root, restricted Pod Security, NetworkPolicy +- CI: lint and house code rules, tests with a 95% coverage gate, Docker builds, manifest validation, Terraform validation, end-to-end on kind including the NetworkPolicy - Image publishing to GitHub Container Registry, one image per service - Dependabot, CodeQL, SHA-pinned actions ## Dropped -- **`utility-api`** (Base64, JWT decode, cron explain, hashing). These tools are already widely available, so building them would add clutter rather than value. +- **`utility-api`** (Base64, JWT decode, cron explain, hashing). These tools are widely available already, so building them would add clutter. ## Out of scope -These are deliberately not planned: +The project leaves these to other tools: - User accounts and authentication - Database or persistent storage diff --git a/scripts/check_code_rules.py b/scripts/check_code_rules.py new file mode 100644 index 0000000..5259986 --- /dev/null +++ b/scripts/check_code_rules.py @@ -0,0 +1,246 @@ +"""Checks the house rules that ruff has no setting for. Run by `make lint` and CI. + +Python, every file: + - no function or lambda defined inside another function, and no lambdas at all + - no `*` or `**` syntax: star imports, *args, **kwargs, keyword-only markers, unpacking + - imports only at the top of the module, before any other statement + - no comments that silence a checker: noqa, type: ignore, pragma: no cover, nosec... +Python, outside tests/: + - a docstring on every module, class and function, and a return type on every function +Markdown (README.md, CONTRIBUTING.md, SECURITY.md, docs/): + - no apostrophes, no comma before "and" or "or", no em dashes (code is left alone) + +Usage: python scripts/check_code_rules.py [path ...] (default: the whole repository) +""" + +from __future__ import annotations + +import ast +import re +import sys +from dataclasses import dataclass +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +SKIPPED_DIRECTORIES = frozenset({".venv", "node_modules", ".git", "__pycache__", "vendor"}) +MARKDOWN_FILES = ("README.md", "CONTRIBUTING.md", "SECURITY.md") +MARKDOWN_DIRECTORY = "docs" +SILENCERS = re.compile( + r"#\s*(noqa|type:\s*ignore|pragma:\s*no\s*cover|nosec|fmt:\s*(off|skip)|pylint:\s*disable)", + re.IGNORECASE, +) +FENCED_CODE = re.compile(r"^```.*?^```", re.MULTILINE | re.DOTALL) +INLINE_CODE = re.compile(r"`[^`\n]*`") +LINK_TARGET = re.compile(r"\]\([^)]*\)") +MARKDOWN_RULES = ( + (re.compile(r"['’]"), "apostrophe"), + (re.compile(r",\s+(and|or)\b"), "comma before 'and' or 'or'"), + (re.compile("—"), "em dash"), +) + + +@dataclass(frozen=True) +class Problem: + """One broken rule at one place.""" + + path: Path + line: int + message: str + + def __str__(self) -> str: + """`path:line: message`, relative to the repository.""" + return f"{self.path.relative_to(ROOT)}:{self.line}: {self.message}" + + +class PythonRules(ast.NodeVisitor): + """Walks one Python module and collects the rules it breaks.""" + + def __init__(self, path: Path, source: str) -> None: + """Prepare to check `source`, read from `path`.""" + self.path = path + self.source = source + self.problems: list[Problem] = [] + self.function_depth = 0 + self.is_test = "tests" in path.parts + + def check(self) -> list[Problem]: + """Every problem in the module.""" + tree = ast.parse(self.source, filename=str(self.path)) + self.check_imports(tree) + self.check_silencers() + if not self.is_test and ast.get_docstring(tree) is None: + self.add(1, "module has no docstring") + self.visit(tree) + return self.problems + + def add(self, line: int, message: str) -> None: + """Record a problem.""" + self.problems.append(Problem(self.path, line, message)) + + def check_imports(self, tree: ast.Module) -> None: + """Imports come first: only a docstring may precede them, and none come later.""" + body = list(tree.body) + if body and ast.get_docstring(tree) is not None: + body = body[1:] + seen_code = False + for statement in body: + is_import = isinstance(statement, ast.Import | ast.ImportFrom) + if is_import and seen_code: + self.add(statement.lineno, "import after other statements") + if not is_import: + seen_code = True + for node in ast.walk(tree): + if isinstance(node, ast.Import | ast.ImportFrom) and node not in tree.body: + self.add(node.lineno, "import inside a function, class or block") + + def check_silencers(self) -> None: + """No comment may switch a checker off.""" + for number, line in enumerate(self.source.splitlines(), start=1): + if SILENCERS.search(line): + self.add(number, "comment that silences a checker") + + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: + """Functions: not nested, documented, typed, no star parameters.""" + self.check_function(node) + + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: + """Async functions follow the same rules as functions.""" + self.check_function(node) + + def check_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: + """The rules for one function or method, then its body.""" + if self.function_depth: + self.add(node.lineno, f"function '{node.name}' defined inside another function") + arguments = node.args + if arguments.vararg or arguments.kwarg or arguments.kwonlyargs: + self.add(node.lineno, f"'{node.name}' uses * or ** in its parameters") + if not self.is_test: + if ast.get_docstring(node) is None: + self.add(node.lineno, f"function '{node.name}' has no docstring") + if node.returns is None: + self.add(node.lineno, f"function '{node.name}' has no return type") + self.function_depth += 1 + self.generic_visit(node) + self.function_depth -= 1 + + def visit_ClassDef(self, node: ast.ClassDef) -> None: + """Classes are documented outside tests.""" + if not self.is_test and ast.get_docstring(node) is None: + self.add(node.lineno, f"class '{node.name}' has no docstring") + self.generic_visit(node) + + def visit_Lambda(self, node: ast.Lambda) -> None: + """No lambdas: name the function.""" + self.add(node.lineno, "lambda") + self.generic_visit(node) + + def visit_Starred(self, node: ast.Starred) -> None: + """No `*` unpacking.""" + self.add(node.lineno, "* unpacking") + self.generic_visit(node) + + def visit_Call(self, node: ast.Call) -> None: + """No `**` in calls.""" + for keyword in node.keywords: + if keyword.arg is None: + self.add(node.lineno, "** unpacking in a call") + self.generic_visit(node) + + def visit_Dict(self, node: ast.Dict) -> None: + """No `**` in dict literals.""" + if any(key is None for key in node.keys): + self.add(node.lineno, "** unpacking in a dict") + self.generic_visit(node) + + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: + """No star imports.""" + if any(alias.name == "*" for alias in node.names): + self.add(node.lineno, "star import") + + +class MarkdownRules: + """Checks the writing rules on one Markdown file, outside code.""" + + def __init__(self, path: Path, text: str) -> None: + """Prepare to check `text`, read from `path`.""" + self.path = path + self.text = text + + def prose(self) -> str: + """The text with code blocks, inline code and link targets replaced by filler of the + same length, keeping line numbers. The filler is letters, so `a`, `b` and c still + reads as a list.""" + text = FENCED_CODE.sub(self.blank, self.text) + text = INLINE_CODE.sub(self.blank, text) + return LINK_TARGET.sub(self.blank, text) + + @staticmethod + def blank(match: re.Match[str]) -> str: + """The matched text with everything but newlines replaced by x.""" + return re.sub(r"[^\n]", "x", match.group(0)) + + def check(self) -> list[Problem]: + """Every problem in the file.""" + problems: list[Problem] = [] + for number, line in enumerate(self.prose().splitlines(), start=1): + for pattern, message in MARKDOWN_RULES: + if pattern.search(line): + problems.append(Problem(self.path, number, message)) + return problems + + +class Repository: + """Finds the files to check.""" + + def __init__(self, root: Path) -> None: + """A repository rooted at `root`.""" + self.root = root + + def python_files(self) -> list[Path]: + """Every Python file outside virtual environments and build output.""" + return sorted(path for path in self.root.rglob("*.py") if self.included(path)) + + def markdown_files(self) -> list[Path]: + """The top-level documents and everything in docs/.""" + files = [self.root / name for name in MARKDOWN_FILES if (self.root / name).exists()] + return files + sorted((self.root / MARKDOWN_DIRECTORY).rglob("*.md")) + + def included(self, path: Path) -> bool: + """Whether `path` is outside the skipped directories.""" + return not SKIPPED_DIRECTORIES.intersection(path.relative_to(self.root).parts) + + +class Checker: + """Runs every rule on a set of files.""" + + def __init__(self, paths: list[Path]) -> None: + """Check `paths`, or the whole repository when it is empty.""" + repository = Repository(ROOT) + if paths: + self.python = [path for path in paths if path.suffix == ".py"] + self.markdown = [path for path in paths if path.suffix == ".md"] + else: + self.python = repository.python_files() + self.markdown = repository.markdown_files() + + def run(self) -> list[Problem]: + """Every problem found.""" + problems: list[Problem] = [] + for path in self.python: + problems.extend(PythonRules(path, path.read_text(encoding="utf-8")).check()) + for path in self.markdown: + problems.extend(MarkdownRules(path, path.read_text(encoding="utf-8")).check()) + return problems + + +def main(arguments: list[str]) -> int: + """Print every problem; exit status 1 when there is any.""" + problems = Checker([Path(argument).resolve() for argument in arguments]).run() + for problem in problems: + print(problem) + print(f"{len(problems)} problem(s)" if problems else "Code rules: all checks passed") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/validate-terraform.sh b/scripts/validate-terraform.sh new file mode 100755 index 0000000..111c97b --- /dev/null +++ b/scripts/validate-terraform.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Convert the CloudFormation fixtures to Terraform and check each result with +# `terraform fmt -check`, `terraform init` and `terraform validate`. Warnings count as +# failures. Each fixture is converted twice (aws provider with separate files and import +# blocks, awscc provider in one file) by services/converter-api/tools/convert_fixtures.py. +# +# Usage: scripts/validate-terraform.sh [fixture ...] (default: every fixture) +# Needs terraform on PATH and access to the Terraform registry. Set TF_PLUGIN_CACHE_DIR to +# download each provider once. PYTHON names the interpreter (default: python3). +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +SERVICE_DIR="${ROOT_DIR}/services/converter-api" +PYTHON="${PYTHON:-python3}" +# A relative interpreter path is relative to where the script was started. +if [[ "$PYTHON" == */* ]]; then + PYTHON="$(cd "$(dirname "$PYTHON")" && pwd)/$(basename "$PYTHON")" +fi + +OUT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/cfn-tf-XXXXXX")" +trap 'rm -rf "$OUT_DIR"' EXIT + +(cd "$SERVICE_DIR" && "$PYTHON" -m tools.convert_fixtures "$OUT_DIR" "$@") + +failed=0 +for dir in "$OUT_DIR"/*/*/; do + dir="${dir%/}" + label="$(basename "$(dirname "$dir")") ($(basename "$dir"))" + problems="" + if ! output="$(terraform -chdir="$dir" fmt -check -diff -no-color 2>&1)"; then + problems+="terraform fmt:"$'\n'"${output}"$'\n' + fi + if ! output="$(terraform -chdir="$dir" init -backend=false -input=false -no-color 2>&1)"; then + problems+="terraform init:"$'\n'"${output}"$'\n' + else + # validate exits 1 on errors; the JSON report on stdout lists errors and warnings. + report="$(terraform -chdir="$dir" validate -json -no-color 2>"${OUT_DIR}/stderr" || true)" + if ! output="$(cd "$SERVICE_DIR" && printf '%s' "$report" | "$PYTHON" -m tools.validate_report)"; then + problems+="${output}"$'\n'"$(cat "${OUT_DIR}/stderr")"$'\n' + fi + fi + if [[ -n "$problems" ]]; then + echo "FAIL ${label}" + printf '%s' "$problems" | sed 's/^/ /' + failed=1 + else + echo "ok ${label}" + fi +done +exit "$failed" diff --git a/services/converter-api/.dockerignore b/services/converter-api/.dockerignore index ad97aac..69b4ec6 100644 --- a/services/converter-api/.dockerignore +++ b/services/converter-api/.dockerignore @@ -7,3 +7,4 @@ __pycache__/ htmlcov/ requirements-dev.txt pyproject.toml +tools/ diff --git a/services/converter-api/Dockerfile b/services/converter-api/Dockerfile index 26cfdf4..d93b397 100644 --- a/services/converter-api/Dockerfile +++ b/services/converter-api/Dockerfile @@ -25,7 +25,7 @@ RUN groupadd --system --gid 10001 app \ COPY --from=builder /opt/venv /opt/venv WORKDIR /app -COPY --chown=app:app main.py . +COPY --chown=app:app main.py schemas.py ./ COPY --chown=app:app converters/ converters/ USER 10001:10001 diff --git a/services/converter-api/converters/cfn/__init__.py b/services/converter-api/converters/cfn/__init__.py new file mode 100644 index 0000000..50800ef --- /dev/null +++ b/services/converter-api/converters/cfn/__init__.py @@ -0,0 +1,2 @@ +"""CloudFormation, AWS SAM and AWS CDK (synthesized) templates to Terraform. The entry point +is pipeline.convert_template.""" diff --git a/services/converter-api/converters/cfn/awscc.py b/services/converter-api/converters/cfn/awscc.py new file mode 100644 index 0000000..0170b1a --- /dev/null +++ b/services/converter-api/converters/cfn/awscc.py @@ -0,0 +1,160 @@ +"""Any CloudFormation resource type as an `awscc` provider resource. + +The awscc provider is generated from the CloudFormation resource schemas, so its resources +are the CloudFormation types one to one: `AWS::S3::Bucket` is `awscc_s3_bucket`, property +`BucketName` is attribute `bucket_name`. awscc_index.json, built from the provider schema by +tools/build_awscc_index.py, lists the types awscc has and, per type, the property paths whose +keys stay as written (maps, "m"), the JSON document properties ("j"), the names outside the +usual snake_case rule ("r", "n"), the properties this provider version lacks ("x") and every +settable attribute ("a"). +""" + +from __future__ import annotations + +import json +from functools import cache +from pathlib import Path +from typing import Any + +from converters.cfn import hcl +from converters.cfn.builder import Builder, tags_map +from converters.cfn.expressions import intrinsic_name +from converters.cfn.models import Raw +from converters.cfn.naming import snake + +INDEX_FILE = Path(__file__).with_name("awscc_index.json") +# Properties that hold Lambda code, for code the SAM or CDK step found in a local folder. +CODE_PROPERTIES = {"AWS::Lambda::Function": "Code", "AWS::Lambda::LayerVersion": "Content"} + + +@cache +def awscc_index() -> dict[str, dict[str, Any]]: + """The index, read once.""" + return json.loads(INDEX_FILE.read_text(encoding="utf-8")) + + +def awscc_type(cfn_type: str) -> str | None: + """The awscc resource type for a CloudFormation type, or None when awscc has none.""" + entry = awscc_index().get(cfn_type) + if entry is None: + return None + if "n" in entry: + return entry["n"] + _, service, kind = cfn_type.split("::") + return f"awscc_{service.lower()}_{snake(kind)}" + + +class AwsccShapes: + """What the index says about one resource type.""" + + def __init__(self, cfn_type: str) -> None: + """The index entry of `cfn_type`.""" + entry = awscc_index().get(cfn_type, {}) + self.maps = set(entry.get("m", ())) + self.json = set(entry.get("j", ())) + self.renames: dict[str, str] = entry.get("r", {}) + self.missing = set(entry.get("x", ())) + self.settable = set(entry.get("a", "").split()) + + def name(self, path: str, prop: str) -> str: + """The attribute name of the property at `path`.""" + return self.renames.get(path) or snake(prop) + + +class AwsccConverter: + """Converts one resource with the awscc provider.""" + + def __init__(self, builder: Builder) -> None: + """Convert the resource `builder` holds.""" + self.b = builder + self.ctx = builder.ctx + self.shapes = AwsccShapes(builder.info.cfn_type) + + def convert(self) -> None: + """Every property as an awscc attribute. Properties this awscc version lacks stay + behind for Props.finish() to report.""" + code = CODE_PROPERTIES.get(self.b.info.cfn_type) + if code and self.b.hints.get("code_path"): + self.local_code(code) + for prop in list(self.b.props.values): + name = self.shapes.name(prop, prop) + if prop in self.shapes.missing or name not in self.shapes.settable: + continue + value = self.b.props.take(prop) + if value is not None: + self.b.props.set(name, self.value(value, prop)) + + def local_code(self, prop: str) -> None: + """awscc reads Lambda code from S3 only, so code from a local folder becomes + variables for the bucket and key the user uploads it to.""" + b = self.b + b.props.drop(prop) + path = b.hints["code_path"] + where = f"zipped code of {b.logical_id} (from {path})" + bucket = self.ctx.placeholder_variable( + f"{b.logical_id}_code_bucket", f"The S3 bucket holding the {where}" + ) + key = self.ctx.placeholder_variable( + f"{b.logical_id}_code_key", f"The S3 key of the {where}" + ) + b.props.set(snake(prop), {"s3_bucket": Raw(bucket), "s3_key": Raw(key)}) + self.ctx.note( + f"{b.logical_id}: the awscc provider takes Lambda code from S3 only; zip {path}, " + f"upload it and set {bucket} and {key}; the aws provider zips it for you" + ) + + def value(self, value: Any, path: str) -> Any: + """One property value, shaped the way the attribute at `path` expects.""" + if path in self.shapes.json: + return self.ctx.json(value) + if path in self.shapes.maps and isinstance(value, list): + # Tags written as [{Key, Value}] for a resource whose awscc tags are a map. + return tags_map(self.ctx, value) + if isinstance(value, list): + return self.sequence(value, path) + if not isinstance(value, dict): + return value + function = intrinsic_name(value) + if function == "Fn::If": + return self.conditional(value[function], path, value) + if function is not None: + return self.ctx.expr(value) + if path in self.shapes.maps: + return {str(key): self.ctx.expr(item) for key, item in value.items()} + return self.structure(value, path) + + def sequence(self, items: list[Any], path: str) -> Any: + """A list. As in ExpressionConverter.sequence, NoValue items go and + `!If [C, x, NoValue]` items are filtered.""" + kept = [item for item in items if not self.ctx.is_no_value(item)] + converted = [self.value(item, path) for item in kept] + if any(self.ctx.optional_item(item)[0] for item in kept): + return Raw(f"[for item in {hcl.inline(converted)} : item if item != null]") + return converted + + def conditional(self, args: Any, path: str, original: dict[str, Any]) -> Any: + """An Fn::If with both branches shaped for this path, so their keys are named + right.""" + if not isinstance(args, list) or len(args) != 3: + return self.ctx.expr(original) + name, yes, no = args + yes_text = hcl.inline(self.value(yes, path)) + no_text = hcl.inline(self.value(no, path)) + return Raw(f"{self.ctx.condition(name)} ? {yes_text} : {no_text}") + + def structure(self, value: dict[str, Any], path: str) -> dict[str, Any]: + """A nested object with attribute names from the index.""" + result: dict[str, Any] = {} + for key, item in value.items(): + child = f"{path}.{key}" + if self.ctx.is_no_value(item): + continue + if child in self.shapes.missing: + self.ctx.note( + f"{self.b.logical_id} ({self.b.info.cfn_type}): property " + f"'{self.b.logical_id}.{child}' is missing from {self.b.info.tf_type} in " + "this provider version and was left out; set it by hand" + ) + continue + result[self.shapes.name(child, str(key))] = self.value(item, child) + return result diff --git a/services/converter-api/converters/cfn/awscc_index.json b/services/converter-api/converters/cfn/awscc_index.json new file mode 100644 index 0000000..eae3b36 --- /dev/null +++ b/services/converter-api/converters/cfn/awscc_index.json @@ -0,0 +1,7168 @@ +{ + "AWS::ACMPCA::Certificate": { + "a": "api_passthrough certificate_authority_arn certificate_signing_request signing_algorithm template_arn validity validity_not_before" + }, + "AWS::ACMPCA::CertificateAuthority": { + "a": "csr_extensions key_algorithm key_storage_security_standard revocation_configuration signing_algorithm subject tags type usage_mode" + }, + "AWS::ACMPCA::CertificateAuthorityActivation": { + "a": "certificate certificate_authority_arn certificate_chain status" + }, + "AWS::ACMPCA::Permission": { + "a": "actions certificate_authority_arn principal source_account" + }, + "AWS::AIOps::InvestigationGroup": { + "a": "chatbot_notification_channels cross_account_configurations encryption_config investigation_group_policy is_cloud_trail_event_history_enabled name retention_in_days role_arn tag_key_boundaries tags" + }, + "AWS::APS::AnomalyDetector": { + "a": "alias configuration evaluation_interval_in_seconds labels missing_data_action tags workspace" + }, + "AWS::APS::ResourcePolicy": { + "a": "policy_document workspace_arn" + }, + "AWS::APS::RuleGroupsNamespace": { + "a": "data name tags workspace" + }, + "AWS::APS::Scraper": { + "a": "alias destination role_configuration scrape_configuration scraper_logging_configuration source tags", + "m": [ + "ScraperLoggingConfiguration.ScraperComponents.Config.Options" + ] + }, + "AWS::APS::Workspace": { + "a": "alert_manager_definition alias kms_key_arn logging_configuration query_logging_configuration tags workspace_configuration" + }, + "AWS::ARCZonalShift::AutoshiftObserverNotificationStatus": { + "a": "status" + }, + "AWS::ARCZonalShift::ZonalAutoshiftConfiguration": { + "a": "practice_run_configuration resource_identifier zonal_autoshift_status" + }, + "AWS::AWSExternalAnthropic::Workspace": { + "a": "data_residency name tags" + }, + "AWS::AccessAnalyzer::Analyzer": { + "a": "analyzer_configuration analyzer_name archive_rules tags type" + }, + "AWS::AccessAnalyzer::ArchiveRule": { + "a": "analyzer_name filter rule_name", + "m": [ + "Filter" + ] + }, + "AWS::AccountAccess::Application": { + "a": "identity_source tags" + }, + "AWS::AccountAccess::Entitlement": { + "a": "application_arn entitlement" + }, + "AWS::AgentRegistry::Registry": { + "a": "approval_configuration authorizer_type auto_detection_enabled auto_detection_scope custom_metadata_schema_configuration description discovery_configuration encryption_configuration name tags" + }, + "AWS::AgentRegistry::RegistryRecord": { + "a": "custom_metadata description descriptors display_name name record_type record_version registry_id tags", + "j": [ + "CustomMetadata" + ], + "m": [ + "Descriptors.A2aAgentCard.Source.FromUrl.CredentialProviderConfigurations.CredentialProvider.OauthCredentialProvider.CustomParameters", + "Descriptors.McpServer.Source.FromUrl.CredentialProviderConfigurations.CredentialProvider.OauthCredentialProvider.CustomParameters" + ], + "r": { + "Descriptors.A2aAgentCard": "a2_a_agent_card" + } + }, + "AWS::AmazonMQ::Configuration": { + "a": "authentication_strategy data description engine_type engine_version name tags" + }, + "AWS::Amplify::App": { + "a": "access_token auto_branch_creation_config basic_auth_config build_spec cache_config compute_role_arn custom_headers custom_rules description enable_branch_auto_deletion environment_variables iam_service_role job_config name oauth_token platform repository tags" + }, + "AWS::Amplify::Branch": { + "a": "app_id backend basic_auth_config branch_name build_spec compute_role_arn description enable_auto_build enable_performance_mode enable_pull_request_preview enable_skew_protection environment_variables framework pull_request_environment_name stage tags" + }, + "AWS::Amplify::Domain": { + "a": "app_id auto_sub_domain_creation_patterns auto_sub_domain_iam_role certificate_settings domain_name enable_auto_sub_domain sub_domain_settings" + }, + "AWS::Amplify::Webhook": { + "a": "app_id branch_name description tags" + }, + "AWS::ApiGateway::Account": { + "a": "cloudwatch_role_arn" + }, + "AWS::ApiGateway::ApiKey": { + "a": "customer_id description enabled generate_distinct_id name stage_keys tags value" + }, + "AWS::ApiGateway::Authorizer": { + "a": "auth_type authorizer_credentials authorizer_result_ttl_in_seconds authorizer_uri identity_source identity_validation_expression name provider_ar_ns rest_api_id type", + "x": [ + "JwtConfiguration" + ] + }, + "AWS::ApiGateway::BasePathMapping": { + "a": "base_path domain_name rest_api_id stage" + }, + "AWS::ApiGateway::BasePathMappingV2": { + "a": "base_path domain_name_arn rest_api_id stage" + }, + "AWS::ApiGateway::ClientCertificate": { + "a": "description tags" + }, + "AWS::ApiGateway::Deployment": { + "a": "deployment_canary_settings description rest_api_id stage_description stage_name", + "m": [ + "DeploymentCanarySettings.StageVariableOverrides", + "StageDescription.CanarySetting.StageVariableOverrides", + "StageDescription.Variables" + ] + }, + "AWS::ApiGateway::DocumentationPart": { + "a": "location properties rest_api_id" + }, + "AWS::ApiGateway::DocumentationVersion": { + "a": "description documentation_version rest_api_id" + }, + "AWS::ApiGateway::DomainName": { + "a": "certificate_arn domain_name endpoint_access_mode endpoint_configuration mutual_tls_authentication ownership_verification_certificate_arn regional_certificate_arn routing_mode security_policy tags" + }, + "AWS::ApiGateway::DomainNameAccessAssociation": { + "a": "access_association_source access_association_source_type domain_name_arn tags" + }, + "AWS::ApiGateway::DomainNameV2": { + "a": "certificate_arn domain_name endpoint_access_mode endpoint_configuration policy routing_mode security_policy tags", + "j": [ + "Policy" + ] + }, + "AWS::ApiGateway::GatewayResponse": { + "a": "response_parameters response_templates response_type rest_api_id status_code", + "m": [ + "ResponseParameters", + "ResponseTemplates" + ] + }, + "AWS::ApiGateway::Method": { + "a": "api_key_required authorization_scopes authorization_type authorizer_id http_method integration method_responses operation_name request_models request_parameters request_validator_id resource_id rest_api_id", + "m": [ + "Integration.IntegrationResponses.ResponseParameters", + "Integration.IntegrationResponses.ResponseTemplates", + "Integration.RequestParameters", + "Integration.RequestTemplates", + "MethodResponses.ResponseModels", + "MethodResponses.ResponseParameters", + "RequestModels", + "RequestParameters" + ] + }, + "AWS::ApiGateway::Model": { + "a": "content_type description name rest_api_id schema", + "j": [ + "Schema" + ] + }, + "AWS::ApiGateway::RequestValidator": { + "a": "name rest_api_id validate_request_body validate_request_parameters" + }, + "AWS::ApiGateway::Resource": { + "a": "parent_id path_part rest_api_id" + }, + "AWS::ApiGateway::RestApi": { + "a": "api_key_source_type binary_media_types body body_s3_location clone_from description disable_execute_api_endpoint endpoint_access_mode endpoint_configuration fail_on_warnings minimum_compression_size mode name parameters policy security_policy tags version", + "j": [ + "Body", + "Parameters", + "Policy" + ] + }, + "AWS::ApiGateway::Stage": { + "a": "access_log_setting cache_cluster_enabled cache_cluster_size canary_setting client_certificate_id deployment_id description documentation_version method_settings rest_api_id stage_name tags tracing_enabled variables", + "m": [ + "CanarySetting.StageVariableOverrides", + "Variables" + ] + }, + "AWS::ApiGateway::UsagePlan": { + "a": "api_stages description quota tags throttle usage_plan_name", + "m": [ + "ApiStages.Throttle" + ] + }, + "AWS::ApiGateway::UsagePlanKey": { + "a": "key_id key_type usage_plan_id" + }, + "AWS::ApiGateway::VpcLink": { + "a": "description name tags target_arns" + }, + "AWS::ApiGatewayV2::Api": { + "a": "api_key_selection_expression base_path body body_s3_location cors_configuration credentials_arn description disable_execute_api_endpoint disable_schema_validation fail_on_warnings ip_address_type name protocol_type route_key route_selection_expression tags target version", + "j": [ + "Body" + ], + "m": [ + "Tags" + ] + }, + "AWS::ApiGatewayV2::ApiGatewayManagedOverrides": { + "a": "api_id integration route stage", + "m": [ + "Stage.RouteSettings", + "Stage.StageVariables" + ] + }, + "AWS::ApiGatewayV2::ApiMapping": { + "a": "api_id api_mapping_key domain_name stage" + }, + "AWS::ApiGatewayV2::Authorizer": { + "a": "api_id authorizer_credentials_arn authorizer_payload_format_version authorizer_result_ttl_in_seconds authorizer_type authorizer_uri enable_simple_responses identity_source identity_validation_expression jwt_configuration name" + }, + "AWS::ApiGatewayV2::Deployment": { + "a": "api_id description stage_name" + }, + "AWS::ApiGatewayV2::DomainName": { + "a": "domain_name domain_name_configurations mutual_tls_authentication routing_mode tags", + "m": [ + "Tags" + ] + }, + "AWS::ApiGatewayV2::Integration": { + "a": "api_id connection_id connection_type content_handling_strategy credentials_arn description integration_method integration_subtype integration_type integration_uri passthrough_behavior payload_format_version request_parameters request_templates response_parameters template_selection_expression timeout_in_millis tls_config", + "m": [ + "RequestParameters", + "RequestTemplates", + "ResponseParameters" + ] + }, + "AWS::ApiGatewayV2::IntegrationResponse": { + "a": "api_id content_handling_strategy integration_id integration_response_key response_parameters response_templates template_selection_expression", + "j": [ + "ResponseParameters", + "ResponseTemplates" + ] + }, + "AWS::ApiGatewayV2::Model": { + "a": "api_id content_type description name schema", + "j": [ + "Schema" + ] + }, + "AWS::ApiGatewayV2::PortalProduct": { + "a": "description display_name tags" + }, + "AWS::ApiGatewayV2::Route": { + "a": "api_id api_key_required authorization_scopes authorization_type authorizer_id model_selection_expression operation_name request_models request_parameters route_key route_response_selection_expression target", + "j": [ + "RequestModels", + "RequestParameters" + ] + }, + "AWS::ApiGatewayV2::RouteResponse": { + "a": "api_id model_selection_expression response_models response_parameters route_id route_response_key", + "j": [ + "ResponseModels" + ], + "m": [ + "ResponseParameters" + ] + }, + "AWS::ApiGatewayV2::RoutingRule": { + "a": "actions conditions domain_name_arn priority" + }, + "AWS::ApiGatewayV2::Stage": { + "a": "access_log_settings api_id auto_deploy client_certificate_id default_route_settings deployment_id description route_settings stage_name stage_variables tags", + "j": [ + "RouteSettings", + "StageVariables", + "Tags" + ] + }, + "AWS::ApiGatewayV2::VpcLink": { + "a": "name security_group_ids subnet_ids tags", + "m": [ + "Tags" + ] + }, + "AWS::AppConfig::Application": { + "a": "description name tags" + }, + "AWS::AppConfig::ConfigurationProfile": { + "a": "application_id deletion_protection_check description kms_key_identifier location_uri name retrieval_role_arn tags type validators" + }, + "AWS::AppConfig::Deployment": { + "a": "application_id configuration_profile_id configuration_version deployment_strategy_id description dynamic_extension_parameters environment_id kms_key_identifier tags" + }, + "AWS::AppConfig::DeploymentStrategy": { + "a": "deployment_duration_in_minutes description final_bake_time_in_minutes growth_factor growth_type name replicate_to tags" + }, + "AWS::AppConfig::Environment": { + "a": "application_id deletion_protection_check description monitors name tags" + }, + "AWS::AppConfig::ExperimentDefinition": { + "a": "application_identifier audience_description audience_rule configuration_profile_identifier control environment_identifier flag_key hypothesis launch_criteria name tags treatments", + "m": [ + "Control.AttributeValues", + "Treatments.AttributeValues" + ] + }, + "AWS::AppConfig::ExperimentRun": { + "a": "application_identifier description experiment_definition_identifier exposure_percentage tags treatment_overrides", + "m": [ + "TreatmentOverrides.Inline" + ] + }, + "AWS::AppConfig::Extension": { + "a": "actions description latest_version_number name parameters tags", + "m": [ + "Actions", + "Parameters" + ] + }, + "AWS::AppConfig::ExtensionAssociation": { + "a": "extension_identifier extension_version_number parameters resource_identifier tags", + "m": [ + "Parameters" + ] + }, + "AWS::AppConfig::HostedConfigurationVersion": { + "a": "application_id configuration_profile_id content content_type description latest_version_number version_label" + }, + "AWS::AppFabric::AppAuthorization": { + "a": "app app_bundle_identifier auth_type credential tags tenant" + }, + "AWS::AppFabric::AppBundle": { + "a": "customer_managed_key_identifier tags" + }, + "AWS::AppFabric::Ingestion": { + "a": "app app_bundle_arn ingestion_type tags tenant_id" + }, + "AWS::AppFabric::IngestionDestination": { + "a": "app_bundle_arn destination_configuration ingestion_arn processing_configuration tags" + }, + "AWS::AppFlow::Connector": { + "a": "connector_label connector_provisioning_config connector_provisioning_type description" + }, + "AWS::AppFlow::ConnectorProfile": { + "a": "connection_mode connector_label connector_profile_config connector_profile_name connector_type kms_arn", + "m": [ + "ConnectorProfileConfig.ConnectorProfileCredentials.CustomConnector.Custom.CredentialsMap", + "ConnectorProfileConfig.ConnectorProfileProperties.CustomConnector.OAuth2Properties.TokenUrlCustomProperties", + "ConnectorProfileConfig.ConnectorProfileProperties.CustomConnector.ProfileProperties" + ], + "x": [ + "ConnectorProfileConfig.ConnectorProfileCredentials.Salesforce.JwtToken", + "ConnectorProfileConfig.ConnectorProfileCredentials.Salesforce.OAuth2GrantType", + "ConnectorProfileConfig.ConnectorProfileCredentials.ServiceNow.OAuth2Credentials", + "ConnectorProfileConfig.ConnectorProfileProperties.SAPOData.DisableSSO", + "ConnectorProfileConfig.ConnectorProfileProperties.Salesforce.usePrivateLinkForMetadataAndAuthorization" + ] + }, + "AWS::AppFlow::Flow": { + "a": "description destination_flow_config_list flow_name flow_status kms_arn metadata_catalog_config source_flow_config tags tasks trigger_config", + "m": [ + "DestinationFlowConfigList.DestinationConnectorProperties.CustomConnector.CustomProperties", + "SourceFlowConfig.SourceConnectorProperties.CustomConnector.CustomProperties" + ] + }, + "AWS::AppIntegrations::Application": { + "a": "application_config application_source_config application_type description iframe_config initialization_timeout is_service name namespace permissions tags", + "x": [ + "AuthConfig", + "LastModifiedRegion", + "LastModifiedTime" + ] + }, + "AWS::AppIntegrations::DataIntegration": { + "a": "description file_configuration kms_key name object_configuration schedule_config source_uri tags", + "m": [ + "FileConfiguration.Filters", + "ObjectConfiguration" + ] + }, + "AWS::AppIntegrations::EventIntegration": { + "a": "description event_bridge_bus event_filter name tags" + }, + "AWS::AppRunner::AutoScalingConfiguration": { + "a": "auto_scaling_configuration_name max_concurrency max_size min_size tags" + }, + "AWS::AppRunner::ObservabilityConfiguration": { + "a": "observability_configuration_name tags trace_configuration" + }, + "AWS::AppRunner::Service": { + "a": "auto_scaling_configuration_arn encryption_configuration health_check_configuration instance_configuration network_configuration observability_configuration service_name source_configuration tags" + }, + "AWS::AppRunner::VpcConnector": { + "a": "security_groups subnets tags vpc_connector_name" + }, + "AWS::AppRunner::VpcIngressConnection": { + "a": "ingress_vpc_configuration service_arn tags vpc_ingress_connection_name" + }, + "AWS::AppStream::AppBlock": { + "a": "description display_name name packaging_type post_setup_script_details setup_script_details source_s3_location tags" + }, + "AWS::AppStream::AppBlockBuilder": { + "a": "access_endpoints app_block_arns description disable_imdsv1 display_name enable_default_internet_access iam_role_arn instance_type name platform tags vpc_config", + "r": { + "DisableIMDSV1": "disable_imdsv1" + } + }, + "AWS::AppStream::Application": { + "a": "app_block_arn attributes_to_delete description display_name icon_s3_location instance_families launch_parameters launch_path name platforms tags working_directory" + }, + "AWS::AppStream::ApplicationEntitlementAssociation": { + "a": "application_identifier entitlement_name stack_name" + }, + "AWS::AppStream::ApplicationFleetAssociation": { + "a": "application_arn fleet_name" + }, + "AWS::AppStream::DirectoryConfig": { + "a": "certificate_based_auth_properties directory_name organizational_unit_distinguished_names service_account_credentials" + }, + "AWS::AppStream::Entitlement": { + "a": "app_visibility attributes description name stack_name" + }, + "AWS::AppStream::Fleet": { + "a": "attributes_to_delete compute_capacity description disable_imdsv1 disconnect_timeout_in_seconds display_name domain_join_info enable_default_internet_access fleet_type iam_role_arn idle_disconnect_timeout_in_seconds image_arn image_name instance_type max_concurrent_sessions max_sessions_per_instance max_user_duration_in_seconds name platform root_volume_config session_script_s3_location stream_view tags usb_device_filter_strings vpc_config", + "r": { + "DisableIMDSV1": "disable_imdsv1" + } + }, + "AWS::AppStream::ImageBuilder": { + "a": "access_endpoints appstream_agent_version description disable_imdsv1 display_name domain_join_info enable_default_internet_access iam_role_arn image_arn image_name instance_type name root_volume_config softwares_to_install softwares_to_uninstall tags vpc_config", + "r": { + "DisableIMDSV1": "disable_imdsv1" + }, + "x": [ + "AgentAccessConfig" + ] + }, + "AWS::AppStream::Stack": { + "a": "access_endpoints agent_access_config application_settings attributes_to_delete content_redirection delete_storage_connectors description display_name embed_host_domains feedback_url name redirect_url storage_connector_authentication storage_connectors streaming_experience_settings tags user_settings", + "x": [ + "AgentAccessConfig.KmsKeyArn", + "AgentAccessConfig.ReplaySessionEnabled" + ] + }, + "AWS::AppStream::StackFleetAssociation": { + "a": "fleet_name stack_name" + }, + "AWS::AppStream::StackUserAssociation": { + "a": "authentication_type send_email_notification stack_name user_name" + }, + "AWS::AppStream::User": { + "a": "authentication_type first_name last_name message_action user_name" + }, + "AWS::AppSync::Api": { + "a": "event_config name owner_contact tags" + }, + "AWS::AppSync::ApiCache": { + "a": "api_caching_behavior api_id at_rest_encryption_enabled health_metrics_config transit_encryption_enabled ttl type" + }, + "AWS::AppSync::ApiKey": { + "a": "api_id description expires" + }, + "AWS::AppSync::ChannelNamespace": { + "a": "api_id code_handlers code_s3_location handler_configs name publish_auth_modes subscribe_auth_modes tags" + }, + "AWS::AppSync::DataSource": { + "a": "api_id description dynamo_db_config elasticsearch_config event_bridge_config http_config lambda_config metrics_config name open_search_service_config relational_database_config service_role_arn type" + }, + "AWS::AppSync::DomainName": { + "a": "certificate_arn description domain_name tags" + }, + "AWS::AppSync::DomainNameApiAssociation": { + "a": "api_id domain_name" + }, + "AWS::AppSync::FunctionConfiguration": { + "a": "api_id code code_s3_location data_source_name description function_version max_batch_size name request_mapping_template request_mapping_template_s3_location response_mapping_template response_mapping_template_s3_location runtime sync_config" + }, + "AWS::AppSync::GraphQLApi": { + "a": "additional_authentication_providers api_type authentication_type enhanced_metrics_config environment_variables introspection_config lambda_authorizer_config log_config merged_api_execution_role_arn name open_id_connect_config owner_contact query_depth_limit resolver_count_limit tags user_pool_config visibility xray_enabled", + "m": [ + "EnvironmentVariables" + ] + }, + "AWS::AppSync::Resolver": { + "a": "api_id caching_config code code_s3_location data_source_name field_name kind max_batch_size metrics_config pipeline_config request_mapping_template request_mapping_template_s3_location response_mapping_template response_mapping_template_s3_location runtime sync_config type_name" + }, + "AWS::AppSync::SourceApiAssociation": { + "a": "description merged_api_identifier source_api_association_config source_api_identifier" + }, + "AWS::AppSync::Type": { + "a": "api_id definition format" + }, + "AWS::AppTest::TestCase": { + "a": "description name steps tags", + "m": [ + "Tags" + ] + }, + "AWS::ApplicationAutoScaling::ScalableTarget": { + "a": "max_capacity min_capacity resource_id role_arn scalable_dimension scheduled_actions service_namespace suspended_state tags" + }, + "AWS::ApplicationAutoScaling::ScalingPolicy": { + "a": "policy_name policy_type predictive_scaling_policy_configuration resource_id scalable_dimension scaling_target_id service_namespace step_scaling_policy_configuration target_tracking_scaling_policy_configuration" + }, + "AWS::ApplicationInsights::Application": { + "a": "attach_missing_permission auto_configuration_enabled component_monitoring_settings custom_components cwe_monitor_enabled grouping_type log_pattern_sets ops_center_enabled ops_item_sns_topic_arn resource_group_name sns_notification_arn tags" + }, + "AWS::ApplicationSignals::Discovery": {}, + "AWS::ApplicationSignals::GroupingConfiguration": { + "a": "grouping_attribute_definitions" + }, + "AWS::ApplicationSignals::InstrumentationConfig": { + "a": "attribute_filters capture_configuration description environment expires_at instrumentation_type location service signal_type tags" + }, + "AWS::ApplicationSignals::ServiceLevelObjective": { + "a": "burn_rate_configurations description exclusion_windows goal name request_based_sli sli tags", + "m": [ + "RequestBasedSli.RequestBasedSliMetric.DependencyConfig.DependencyKeyAttributes", + "RequestBasedSli.RequestBasedSliMetric.KeyAttributes", + "RequestBasedSli.RequestBasedSliMetric.MetricSource.MetricSourceAttributes", + "RequestBasedSli.RequestBasedSliMetric.MetricSource.MetricSourceKeyAttributes", + "Sli.SliMetric.DependencyConfig.DependencyKeyAttributes", + "Sli.SliMetric.KeyAttributes", + "Sli.SliMetric.MetricSource.MetricSourceAttributes", + "Sli.SliMetric.MetricSource.MetricSourceKeyAttributes" + ] + }, + "AWS::Athena::CapacityReservation": { + "a": "capacity_assignment_configuration name tags target_dpus" + }, + "AWS::Athena::DataCatalog": { + "a": "connection_type description error name parameters status tags type", + "m": [ + "Parameters" + ] + }, + "AWS::Athena::NamedQuery": { + "a": "database description name query_string work_group" + }, + "AWS::Athena::PreparedStatement": { + "a": "description query_statement statement_name work_group" + }, + "AWS::Athena::WorkGroup": { + "a": "description name recursive_delete_option state tags work_group_configuration work_group_configuration_updates", + "m": [ + "WorkGroupConfiguration.EngineConfiguration.AdditionalConfigs", + "WorkGroupConfiguration.EngineConfiguration.Classifications.Properties", + "WorkGroupConfiguration.EngineConfiguration.SparkProperties", + "WorkGroupConfiguration.MonitoringConfiguration.CloudWatchLoggingConfiguration.LogTypes", + "WorkGroupConfigurationUpdates.EngineConfiguration.AdditionalConfigs", + "WorkGroupConfigurationUpdates.EngineConfiguration.Classifications.Properties", + "WorkGroupConfigurationUpdates.EngineConfiguration.SparkProperties", + "WorkGroupConfigurationUpdates.MonitoringConfiguration.CloudWatchLoggingConfiguration.LogTypes" + ] + }, + "AWS::AuditManager::Assessment": { + "a": "assessment_reports_destination aws_account delegations description framework_id name roles scope status tags" + }, + "AWS::AuditManager::AssessmentFramework": { + "a": "compliance_type control_sets description name tags" + }, + "AWS::AutoScaling::AutoScalingGroup": { + "a": "auto_scaling_group_name availability_zone_distribution availability_zone_ids availability_zone_impairment_policy availability_zones capacity_rebalance capacity_reservation_specification context cooldown default_instance_warmup deletion_protection desired_capacity desired_capacity_type health_check_grace_period health_check_type instance_id instance_lifecycle_policy instance_maintenance_policy launch_configuration_name launch_template lifecycle_hook_specification_list load_balancer_names max_instance_lifetime max_size metrics_collection min_size mixed_instances_policy new_instances_protected_from_scale_in notification_configuration notification_configurations placement_group service_linked_role_arn skip_zonal_shift_validation tags target_group_ar_ns termination_policies traffic_sources vpc_zone_identifier" + }, + "AWS::AutoScaling::LaunchConfiguration": { + "a": "associate_public_ip_address block_device_mappings classic_link_vpc_id classic_link_vpc_security_groups ebs_optimized iam_instance_profile image_id instance_id instance_monitoring instance_type kernel_id key_name launch_configuration_name metadata_options placement_tenancy ram_disk_id security_groups spot_price user_data" + }, + "AWS::AutoScaling::LifecycleHook": { + "a": "auto_scaling_group_name default_result heartbeat_timeout lifecycle_hook_name lifecycle_transition notification_metadata notification_target_arn role_arn" + }, + "AWS::AutoScaling::ScalingPolicy": { + "a": "adjustment_type auto_scaling_group_name cooldown estimated_instance_warmup metric_aggregation_type min_adjustment_magnitude policy_type predictive_scaling_configuration scaling_adjustment step_adjustments target_tracking_configuration" + }, + "AWS::AutoScaling::ScheduledAction": { + "a": "auto_scaling_group_name desired_capacity end_time max_size min_size recurrence start_time time_zone" + }, + "AWS::AutoScaling::WarmPool": { + "a": "auto_scaling_group_name instance_reuse_policy max_group_prepared_capacity min_size pool_state" + }, + "AWS::AutoScalingPlans::ScalingPlan": { + "a": "application_source scaling_instructions" + }, + "AWS::B2BI::Capability": { + "a": "configuration instructions_documents name tags type" + }, + "AWS::B2BI::Partnership": { + "a": "capabilities capability_options email name phone profile_id tags", + "r": { + "CapabilityOptions.InboundEdi.X12": "x12" + } + }, + "AWS::B2BI::Profile": { + "a": "business_name email logging name phone tags" + }, + "AWS::B2BI::Transformer": { + "a": "edi_type file_format input_conversion mapping mapping_template name output_conversion sample_document sample_documents status tags", + "r": { + "InputConversion.AdvancedOptions.X12": "x12", + "OutputConversion.AdvancedOptions.X12": "x12" + } + }, + "AWS::BCM::ScheduledReport": { + "a": "dashboard_arn description name schedule_config scheduled_report_execution_role_arn tags widget_date_range_override widget_ids" + }, + "AWS::BCMDataExports::Export": { + "a": "export tags", + "m": [ + "Export.DataQuery.TableConfigurations" + ] + }, + "AWS::Backup::BackupAccessPoint": { + "a": "access_point_in_time access_point_policy name recovery_point_arn tags", + "j": [ + "AccessPointPolicy" + ] + }, + "AWS::Backup::BackupPlan": { + "a": "backup_plan backup_plan_tags", + "j": [ + "BackupPlan.AdvancedBackupSettings.BackupOptions" + ], + "m": [ + "BackupPlan.BackupPlanRule.RecoveryPointTags", + "BackupPlanTags" + ] + }, + "AWS::Backup::BackupSelection": { + "a": "backup_plan_id backup_selection" + }, + "AWS::Backup::BackupVault": { + "a": "access_policy backup_vault_name backup_vault_tags encryption_key_arn lock_configuration notifications", + "j": [ + "AccessPolicy" + ], + "m": [ + "BackupVaultTags" + ] + }, + "AWS::Backup::Framework": { + "a": "framework_controls framework_description framework_name framework_tags" + }, + "AWS::Backup::LegalHold": { + "a": "description recovery_point_selection tags title" + }, + "AWS::Backup::LogicallyAirGappedBackupVault": { + "a": "access_policy backup_vault_name backup_vault_tags encryption_key_arn max_retention_days min_retention_days mpa_approval_team_arn notifications", + "j": [ + "AccessPolicy" + ], + "m": [ + "BackupVaultTags" + ] + }, + "AWS::Backup::ReportPlan": { + "a": "report_delivery_channel report_plan_description report_plan_name report_plan_tags report_setting" + }, + "AWS::Backup::RestoreTestingPlan": { + "a": "recovery_point_selection restore_testing_plan_name schedule_expression schedule_expression_timezone start_window_hours tags" + }, + "AWS::Backup::RestoreTestingSelection": { + "a": "iam_role_arn protected_resource_arns protected_resource_conditions protected_resource_type restore_metadata_overrides restore_testing_plan_name restore_testing_selection_name validation_window_hours", + "m": [ + "RestoreMetadataOverrides" + ] + }, + "AWS::Backup::TieringConfiguration": { + "a": "backup_vault_name resource_selection tiering_configuration_name tiering_configuration_tags", + "m": [ + "TieringConfigurationTags" + ] + }, + "AWS::BackupGateway::Hypervisor": { + "a": "host kms_key_arn log_group_arn name password tags username" + }, + "AWS::Batch::ComputeEnvironment": { + "a": "compute_environment_name compute_resources context ecs_settings eks_configuration replace_compute_environment service_role state tags type unmanagedv_cpus update_policy", + "m": [ + "ComputeResources.CapacityTags", + "ComputeResources.Tags", + "Tags" + ], + "r": { + "ComputeResources.Ec2Configuration": "ec_2_configuration", + "ComputeResources.Ec2KeyPair": "ec_2_key_pair", + "ComputeResources.ManagedInstancesProvider.InstanceLaunchTemplate.Ec2InstanceProfileArn": "ec_2_instance_profile_arn" + } + }, + "AWS::Batch::ConsumableResource": { + "a": "consumable_resource_name resource_type tags total_quantity", + "m": [ + "Tags" + ] + }, + "AWS::Batch::JobDefinition": { + "a": "consumable_resource_properties container_properties ecs_properties eks_properties job_definition_name node_properties parameters platform_capabilities propagate_tags resource_retention_policy retry_strategy scheduling_priority tags timeout type", + "m": [ + "ContainerProperties.LogConfiguration.Options", + "EcsProperties.TaskProperties.Containers.FirelensConfiguration.Options", + "EcsProperties.TaskProperties.Containers.LogConfiguration.Options", + "EksProperties.PodProperties.Containers.Resources.Limits", + "EksProperties.PodProperties.Containers.Resources.Requests", + "EksProperties.PodProperties.InitContainers.Resources.Limits", + "EksProperties.PodProperties.InitContainers.Resources.Requests", + "EksProperties.PodProperties.Metadata.Annotations", + "EksProperties.PodProperties.Metadata.Labels", + "NodeProperties.NodeRangeProperties.Container.LogConfiguration.Options", + "NodeProperties.NodeRangeProperties.EcsProperties.TaskProperties.Containers.FirelensConfiguration.Options", + "NodeProperties.NodeRangeProperties.EcsProperties.TaskProperties.Containers.LogConfiguration.Options", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.Containers.Resources.Limits", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.Containers.Resources.Requests", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.InitContainers.Resources.Limits", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.InitContainers.Resources.Requests", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.Metadata.Annotations", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.Metadata.Labels", + "Parameters", + "Tags" + ], + "x": [ + "EksProperties.PodProperties.Containers.SecurityContext.Capabilities", + "EksProperties.PodProperties.Containers.SecurityContext.SeccompProfile", + "EksProperties.PodProperties.InitContainers.SecurityContext.Capabilities", + "EksProperties.PodProperties.InitContainers.SecurityContext.SeccompProfile", + "EksProperties.PodProperties.SecurityContext", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.Containers.SecurityContext.Capabilities", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.Containers.SecurityContext.SeccompProfile", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.InitContainers.SecurityContext.Capabilities", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.InitContainers.SecurityContext.SeccompProfile", + "NodeProperties.NodeRangeProperties.EksProperties.PodProperties.SecurityContext" + ] + }, + "AWS::Batch::JobQueue": { + "a": "compute_environment_order job_queue_name job_queue_type job_state_time_limit_actions priority scheduling_policy_arn service_environment_order state tags", + "m": [ + "Tags" + ] + }, + "AWS::Batch::QuotaShare": { + "a": "capacity_limits job_queue preemption_configuration quota_share_name resource_sharing_configuration state tags", + "m": [ + "Tags" + ] + }, + "AWS::Batch::SchedulingPolicy": { + "a": "fairshare_policy name quota_share_policy tags", + "m": [ + "Tags" + ] + }, + "AWS::Batch::ServiceEnvironment": { + "a": "capacity_limits service_environment_name service_environment_type state tags", + "m": [ + "Tags" + ] + }, + "AWS::BcmPricingCalculator::BillEstimate": { + "a": "bill_scenario_id expires_at name tags" + }, + "AWS::BcmPricingCalculator::BillScenario": { + "a": "cost_category_group_sharing_preference_arn expires_at group_sharing_preference name tags" + }, + "AWS::BcmPricingCalculator::WorkloadEstimate": { + "a": "expires_at name rate_type tags" + }, + "AWS::Bedrock::Agent": { + "a": "action_groups agent_collaboration agent_collaborators agent_name agent_resource_role_arn auto_prepare custom_orchestration customer_encryption_key_arn description foundation_model guardrail_configuration idle_session_ttl_in_seconds instruction knowledge_bases memory_configuration orchestration_type prompt_override_configuration skip_resource_in_use_check_on_delete tags test_alias_tags", + "j": [ + "PromptOverrideConfiguration.PromptConfigurations.AdditionalModelRequestFields" + ], + "m": [ + "ActionGroups.FunctionSchema.Functions.Parameters", + "Tags", + "TestAliasTags" + ] + }, + "AWS::Bedrock::AgentAlias": { + "a": "agent_alias_name agent_id description routing_configuration tags", + "m": [ + "Tags" + ] + }, + "AWS::Bedrock::ApplicationInferenceProfile": { + "a": "description inference_profile_name model_source tags" + }, + "AWS::Bedrock::AutomatedReasoningPolicy": { + "a": "description force_delete kms_key_id name policy_definition tags" + }, + "AWS::Bedrock::AutomatedReasoningPolicyVersion": { + "a": "last_updated_definition_hash policy_arn tags" + }, + "AWS::Bedrock::Blueprint": { + "a": "blueprint_name kms_encryption_context kms_key_id schema tags type", + "j": [ + "Schema" + ], + "m": [ + "KmsEncryptionContext" + ] + }, + "AWS::Bedrock::DataAutomationLibrary": { + "a": "encryption_configuration library_description library_name tags", + "m": [ + "EncryptionConfiguration.KmsEncryptionContext" + ] + }, + "AWS::Bedrock::DataAutomationProject": { + "a": "custom_output_configuration kms_encryption_context kms_key_id override_configuration project_description project_name project_type standard_output_configuration tags", + "m": [ + "KmsEncryptionContext" + ] + }, + "AWS::Bedrock::DataSource": { + "a": "data_deletion_policy data_source_configuration description knowledge_base_id name server_side_encryption_configuration vector_ingestion_configuration", + "j": [ + "DataSourceConfiguration.ManagedKnowledgeBaseConnectorConfiguration.ConnectorParameters", + "DataSourceConfiguration.ManagedKnowledgeBaseConnectorConfiguration.SyncSchedule.Daily", + "DataSourceConfiguration.ManagedKnowledgeBaseConnectorConfiguration.SyncSchedule.Monthly.DayOfMonth.LastDayOfMonth" + ] + }, + "AWS::Bedrock::EnforcedGuardrailConfiguration": { + "a": "guardrail_identifier guardrail_version model_enforcement selective_content_guarding" + }, + "AWS::Bedrock::FlowAlias": { + "a": "concurrency_configuration description flow_arn name routing_configuration tags", + "m": [ + "Tags" + ] + }, + "AWS::Bedrock::FlowVersion": { + "a": "description flow_arn" + }, + "AWS::Bedrock::Guardrail": { + "a": "automated_reasoning_policy_config blocked_input_messaging blocked_outputs_messaging content_policy_config contextual_grounding_policy_config cross_region_config description kms_key_arn name sensitive_information_policy_config tags topic_policy_config word_policy_config" + }, + "AWS::Bedrock::GuardrailVersion": { + "a": "description guardrail_identifier" + }, + "AWS::Bedrock::IntelligentPromptRouter": { + "a": "description fallback_model models prompt_router_name routing_criteria tags" + }, + "AWS::Bedrock::KnowledgeBase": { + "a": "description knowledge_base_configuration name role_arn storage_configuration tags", + "j": [ + "KnowledgeBaseConfiguration.ManagedKnowledgeBaseConfiguration.EmbeddingModelConfiguration.BedrockEmbeddingModelConfiguration.ModelConfiguration", + "KnowledgeBaseConfiguration.VectorKnowledgeBaseConfiguration.EmbeddingModelConfiguration.BedrockEmbeddingModelConfiguration.ModelConfiguration" + ], + "m": [ + "Tags" + ] + }, + "AWS::Bedrock::KnowledgeBasePolicy": { + "a": "knowledge_base_id policy_document", + "j": [ + "PolicyDocument" + ] + }, + "AWS::Bedrock::Prompt": { + "a": "customer_encryption_key_arn default_variant description name tags variants", + "j": [ + "Variants.AdditionalModelRequestFields" + ], + "m": [ + "Tags" + ] + }, + "AWS::Bedrock::PromptVersion": { + "a": "description prompt_arn tags", + "j": [ + "Variants.AdditionalModelRequestFields" + ], + "m": [ + "Tags" + ] + }, + "AWS::Bedrock::ResourcePolicy": { + "a": "policy_document resource_arn", + "j": [ + "PolicyDocument" + ] + }, + "AWS::Bedrock::RetrievalInstruction": { + "a": "customer_encryption_key_arn description instruction name tags" + }, + "AWS::Bedrock::Session": { + "a": "encryption_key_arn session_metadata tags", + "m": [ + "SessionMetadata" + ] + }, + "AWS::BedrockAgentCore::ApiKeyCredentialProvider": { + "a": "api_key api_key_secret_config api_key_secret_source name tags" + }, + "AWS::BedrockAgentCore::BrowserCustom": { + "a": "browser_signing certificates description enterprise_policies execution_role_arn name network_configuration recording_config tags", + "m": [ + "Tags" + ] + }, + "AWS::BedrockAgentCore::BrowserProfile": { + "a": "description name tags", + "m": [ + "Tags" + ] + }, + "AWS::BedrockAgentCore::CapacityProvider": { + "a": "compute_configuration description name permissions_configuration tags", + "m": [ + "ComputeConfiguration.Ec2Configuration.LaunchTemplateSource.LaunchParameters.PropagatedTags" + ], + "r": { + "ComputeConfiguration.Ec2Configuration": "ec_2_configuration" + }, + "x": [ + "ComputeConfiguration.Ec2Configuration.LaunchTemplateSource.LaunchParameters.CpuOptions" + ] + }, + "AWS::BedrockAgentCore::CodeInterpreterCustom": { + "a": "certificates description execution_role_arn name network_configuration tags", + "m": [ + "Tags" + ] + }, + "AWS::BedrockAgentCore::ConfigurationBundle": { + "a": "branch_name bundle_name commit_message components created_by description kms_key_arn tags", + "m": [ + "Components" + ] + }, + "AWS::BedrockAgentCore::ConsentPortal": { + "a": "description execution_role_arn idp_config name sources tags" + }, + "AWS::BedrockAgentCore::Evaluator": { + "a": "description evaluator_config evaluator_name kms_key_arn level tags", + "j": [ + "EvaluatorConfig.Derived.ModelConfig.BedrockEvaluatorModelConfig.AdditionalModelRequestFields", + "EvaluatorConfig.LlmAsAJudge.ModelConfig.BedrockEvaluatorModelConfig.AdditionalModelRequestFields" + ], + "x": [ + "Provider" + ] + }, + "AWS::BedrockAgentCore::Gateway": { + "a": "authorizer_configuration authorizer_type description exception_level interceptor_configurations kms_key_arn name policy_engine_configuration protocol_configuration protocol_type role_arn tags waf_configuration", + "m": [ + "Tags" + ] + }, + "AWS::BedrockAgentCore::GatewayRateLimit": { + "a": "description dimension_keys entries gateway_identifier rate_limit_id", + "m": [ + "Entries.Dimensions" + ] + }, + "AWS::BedrockAgentCore::GatewayRule": { + "a": "actions conditions description gateway_identifier priority" + }, + "AWS::BedrockAgentCore::Harness": { + "a": "allowed_tools authorizer_configuration environment environment_artifact environment_variables execution_role_arn harness_name max_iterations max_tokens memory model skills system_prompt tags timeout_seconds tools truncation", + "j": [ + "Tools.Config.AgentCoreGateway.OutboundAuth.AwsIam", + "Tools.Config.AgentCoreGateway.OutboundAuth.None", + "Tools.Config.InlineFunction.InputSchema" + ], + "m": [ + "EnvironmentVariables", + "Memory.AgentCoreMemoryConfiguration.RetrievalConfig", + "Tools.Config.AgentCoreGateway.OutboundAuth.Oauth.CustomParameters", + "Tools.Config.RemoteMcp.Headers" + ], + "x": [ + "AuthorizerConfiguration.CustomJWTAuthorizer.AdvertisedScopeMapping", + "AuthorizerConfiguration.CustomJWTAuthorizer.PrivateEndpoint", + "AuthorizerConfiguration.CustomJWTAuthorizer.PrivateEndpointOverrides", + "Environment.AgentCoreRuntimeEnvironment.FilesystemConfigurations.EfsAccessPoint", + "Environment.AgentCoreRuntimeEnvironment.FilesystemConfigurations.S3FilesAccessPoint", + "Hooks", + "Memory.Disabled", + "Memory.ManagedMemoryConfiguration", + "Model.BedrockModelConfig.AdditionalParams", + "Model.BedrockModelConfig.ApiFormat", + "Model.GeminiModelConfig.AdditionalParams", + "Model.LiteLlmModelConfig", + "Model.OpenAiModelConfig.AdditionalParams", + "Model.OpenAiModelConfig.ApiBase", + "Model.OpenAiModelConfig.ApiFormat", + "Skills.AwsSkills", + "Skills.Git", + "Skills.S3", + "Tools.Config.RemoteMcp.OutboundAuth", + "Version" + ] + }, + "AWS::BedrockAgentCore::HarnessEndpoint": { + "a": "description endpoint_name harness_id tags target_version" + }, + "AWS::BedrockAgentCore::Memory": { + "a": "description encryption_key_arn event_expiry_duration indexed_keys memory_execution_role_arn memory_strategies name namespace_keys stream_delivery_resources tags", + "m": [ + "Tags" + ] + }, + "AWS::BedrockAgentCore::OAuth2CredentialProvider": { + "a": "credential_provider_vendor name oauth_2_provider_config_input tags", + "m": [ + "Oauth2ProviderConfigInput.CustomOauth2ProviderConfig.PrivateEndpoint.ManagedVpcResource.Tags", + "Oauth2ProviderConfigInput.CustomOauth2ProviderConfig.PrivateEndpointOverrides.PrivateEndpoint.ManagedVpcResource.Tags", + "Oauth2ProviderConfigInput.CustomOauth2ProviderConfig.PrivateKeyJwtConfig.AdditionalHeaderClaims", + "Oauth2ProviderConfigInput.CustomOauth2ProviderConfig.PrivateKeyJwtConfig.AdditionalPayloadClaims", + "Oauth2ProviderConfigOutput.PrivateEndpoint.ManagedVpcResource.Tags", + "Oauth2ProviderConfigOutput.PrivateEndpointOverrides.PrivateEndpoint.ManagedVpcResource.Tags", + "Oauth2ProviderConfigOutput.PrivateKeyJwtConfig.AdditionalHeaderClaims", + "Oauth2ProviderConfigOutput.PrivateKeyJwtConfig.AdditionalPayloadClaims" + ], + "x": [ + "Oauth2ProviderConfigInput.CustomOauth2ProviderConfig.CertificateConfigurations", + "Oauth2ProviderConfigOutput.CertificateConfigurations" + ] + }, + "AWS::BedrockAgentCore::OnlineEvaluationConfig": { + "a": "clustering_config data_source_config description evaluation_execution_role_arn evaluators execution_status insights online_evaluation_config_name output_config rule tags" + }, + "AWS::BedrockAgentCore::PaymentConnector": { + "a": "connector_name connector_type credential_provider_configurations description payment_manager_id provision_mode", + "x": [ + "AwsBillingIamRoleArn" + ] + }, + "AWS::BedrockAgentCore::PaymentCredentialProvider": { + "a": "credential_provider_vendor name provider_configuration_input tags" + }, + "AWS::BedrockAgentCore::PaymentManager": { + "a": "authorizer_configuration authorizer_type description name role_arn tags" + }, + "AWS::BedrockAgentCore::Policy": { + "a": "definition description enforcement_mode name policy_engine_id validation_mode" + }, + "AWS::BedrockAgentCore::PolicyEngine": { + "a": "description encryption_key_arn name tags" + }, + "AWS::BedrockAgentCore::ResourcePolicy": { + "a": "policy resource_arn" + }, + "AWS::BedrockAgentCore::Runtime": { + "a": "agent_runtime_artifact agent_runtime_name authorizer_configuration capacity_provider_configuration description environment_variables filesystem_configurations lifecycle_configuration network_configuration platform_version protocol_configuration request_header_configuration role_arn tags", + "m": [ + "EnvironmentVariables", + "Tags" + ], + "x": [ + "HooksConfiguration", + "ResourceConfigurations" + ] + }, + "AWS::BedrockAgentCore::RuntimeEndpoint": { + "a": "agent_runtime_id agent_runtime_version description name tags", + "m": [ + "Tags" + ] + }, + "AWS::BedrockAgentCore::WorkloadIdentity": { + "a": "allowed_resource_oauth_2_return_urls name tags" + }, + "AWS::BedrockMantle::Project": { + "a": "name tags" + }, + "AWS::Billing::BillingView": { + "a": "data_filter_expression description name source_views tags" + }, + "AWS::BillingConductor::BillingGroup": { + "a": "account_grouping computation_preference description name primary_account_id tags" + }, + "AWS::BillingConductor::CustomLineItem": { + "a": "account_id billing_group_arn billing_period_range computation_rule custom_line_item_charge_details description name presentation_details tags" + }, + "AWS::BillingConductor::PricingPlan": { + "a": "description name pricing_rule_arns tags" + }, + "AWS::BillingConductor::PricingRule": { + "a": "billing_entity description modifier_percentage name operation scope service tags tiering type usage_type" + }, + "AWS::Braket::SpendingLimit": { + "a": "device_arn spending_limit tags time_period" + }, + "AWS::Budgets::BudgetsAction": { + "a": "action_threshold action_type approval_model budget_name definition execution_role_arn notification_type resource_tags subscribers" + }, + "AWS::CE::AnomalyMonitor": { + "a": "monitor_dimension monitor_name monitor_specification monitor_type resource_tags" + }, + "AWS::CE::AnomalySubscription": { + "a": "frequency monitor_arn_list resource_tags subscribers subscription_name threshold threshold_expression" + }, + "AWS::CE::CostCategory": { + "a": "default_value name rule_version rules split_charge_rules tags" + }, + "AWS::CUR::ReportDefinition": { + "a": "additional_artifacts additional_schema_elements billing_view_arn compression format refresh_closed_reports report_name report_versioning s3_bucket s3_prefix s3_region tags time_unit" + }, + "AWS::Cases::Case": { + "a": "customer_id domain_id tags template_id title" + }, + "AWS::Cases::CaseRule": { + "a": "description domain_id name rule tags" + }, + "AWS::Cases::Domain": { + "a": "name tags" + }, + "AWS::Cases::Field": { + "a": "attributes description domain_id name tags type" + }, + "AWS::Cases::Layout": { + "a": "content domain_id name tags" + }, + "AWS::Cases::RelatedItem": { + "a": "case_id content domain_id tags type" + }, + "AWS::Cases::Template": { + "a": "description domain_id layout_configuration name required_fields rules status tags" + }, + "AWS::Cassandra::Keyspace": { + "a": "client_side_timestamps_enabled keyspace_name replication_specification tags" + }, + "AWS::Cassandra::Table": { + "a": "auto_scaling_specifications billing_mode cdc_specification client_side_timestamps_enabled clustering_key_columns default_time_to_live encryption_specification keyspace_name partition_key_columns point_in_time_recovery_enabled regular_columns replica_specifications table_name tags warm_throughput" + }, + "AWS::Cassandra::Type": { + "a": "fields keyspace_name type_name" + }, + "AWS::CertificateManager::Account": { + "a": "expiry_events_configuration" + }, + "AWS::CertificateManager::AcmeDomainValidation": { + "a": "acme_endpoint_arn domain_name prevalidation_options tags" + }, + "AWS::CertificateManager::AcmeEndpoint": { + "a": "authorization_behavior certificate_authority certificate_tags contact tags" + }, + "AWS::CertificateManager::AcmeExternalAccountBinding": { + "a": "acme_endpoint_arn expiration role_arn tags" + }, + "AWS::CertificateManager::Certificate": { + "a": "certificate_authority_arn certificate_export certificate_transparency_logging_preference domain_name domain_validation_options key_algorithm subject_alternative_names tags validation_method" + }, + "AWS::Chatbot::CustomAction": { + "a": "action_name alias_name attachments definition tags", + "m": [ + "Attachments.Variables" + ] + }, + "AWS::Chatbot::MicrosoftTeamsChannelConfiguration": { + "a": "configuration_name customization_resource_arns guardrail_policies iam_role_arn logging_level sns_topic_arns tags team_id teams_channel_id teams_channel_name teams_tenant_id user_role_required" + }, + "AWS::Chatbot::SlackChannelConfiguration": { + "a": "configuration_name customization_resource_arns guardrail_policies iam_role_arn logging_level slack_channel_id slack_workspace_id sns_topic_arns tags user_role_required" + }, + "AWS::Chime::AppInstance": { + "a": "metadata name tags" + }, + "AWS::Chime::AppInstanceBot": { + "a": "app_instance_arn configuration metadata name tags" + }, + "AWS::Chime::AppInstanceUser": { + "a": "app_instance_arn app_instance_user_id expiration_settings metadata name tags" + }, + "AWS::Chime::Channel": { + "a": "app_instance_arn channel_id chime_bearer elastic_channel_configuration expiration_settings member_arns metadata mode moderator_arns name privacy tags" + }, + "AWS::Chime::ChannelFlow": { + "a": "app_instance_arn name processors tags" + }, + "AWS::Chime::MediaInsightsPipelineConfiguration": { + "a": "elements media_insights_pipeline_configuration_name real_time_alert_configuration resource_access_role_arn tags" + }, + "AWS::Chime::MediaPipelineKinesisVideoStreamPool": { + "a": "pool_name stream_configuration tags" + }, + "AWS::Chime::SipMediaApplication": { + "a": "aws_region endpoints name tags" + }, + "AWS::Chime::VoiceConnector": { + "a": "aws_region name network_type require_encryption tags" + }, + "AWS::CleanRooms::AnalysisTemplate": { + "a": "analysis_parameters description error_message_configuration format membership_identifier name schema source source_metadata synthetic_data_parameters tags" + }, + "AWS::CleanRooms::Collaboration": { + "a": "allowed_result_regions analytics_engine auto_approved_change_types creator_display_name creator_member_abilities creator_ml_member_abilities creator_payment_configuration data_encryption_metadata description is_metrics_enabled job_log_status members name query_log_status tags" + }, + "AWS::CleanRooms::ConfiguredTable": { + "a": "allowed_columns analysis_method analysis_rules description name selected_analysis_methods table_reference tags", + "r": { + "AnalysisRules.Policy.V1": "v1" + } + }, + "AWS::CleanRooms::ConfiguredTableAssociation": { + "a": "configured_table_association_analysis_rules configured_table_identifier description membership_identifier name role_arn tags", + "r": { + "ConfiguredTableAssociationAnalysisRules.Policy.V1": "v1" + } + }, + "AWS::CleanRooms::IdMappingTable": { + "a": "description input_reference_config kms_key_arn membership_identifier name tags" + }, + "AWS::CleanRooms::IntermediateTable": { + "a": "analysis_rules description kms_key_arn membership_identifier name population_analysis_configuration tags", + "r": { + "AnalysisRules.Policy.V1": "v1" + } + }, + "AWS::CleanRooms::Membership": { + "a": "collaboration_identifier default_job_result_configuration default_result_configuration is_metrics_enabled job_log_status payment_configuration query_log_status tags" + }, + "AWS::CleanRooms::PrivacyBudgetTemplate": { + "a": "auto_refresh membership_identifier parameters privacy_budget_type tags" + }, + "AWS::CleanRoomsML::ConfiguredModelAlgorithm": { + "a": "description inference_container_config kms_key_arn name role_arn tags training_container_config" + }, + "AWS::CleanRoomsML::ConfiguredModelAlgorithmAssociation": { + "a": "configured_model_algorithm_arn description membership_identifier name privacy_configuration tags" + }, + "AWS::CleanRoomsML::TrainingDataset": { + "a": "description name role_arn tags training_data" + }, + "AWS::Cloud9::EnvironmentEC2": { + "a": "automatic_stop_time_minutes connection_type description image_id instance_type name owner_arn repositories subnet_id tags" + }, + "AWS::CloudFormation::ChangeSet": { + "a": "capabilities change_set_name change_set_type deployment_mode description import_existing_resources include_nested_stacks notification_ar_ns on_stack_failure role_arn stack_name tags template_body template_url use_previous_template" + }, + "AWS::CloudFormation::GeneratedTemplate": { + "a": "generated_template_name template_configuration", + "x": [ + "StackId" + ] + }, + "AWS::CloudFormation::GuardHook": { + "a": "alias execution_role failure_mode hook_status log_bucket options rule_location stack_filters target_filters target_operations", + "j": [ + "Options.InputParams" + ] + }, + "AWS::CloudFormation::HookDefaultVersion": { + "a": "type_name type_version_arn version_id" + }, + "AWS::CloudFormation::HookTypeConfig": { + "a": "configuration configuration_alias type_arn type_name" + }, + "AWS::CloudFormation::HookVersion": { + "a": "execution_role_arn logging_config schema_handler_package type_name" + }, + "AWS::CloudFormation::LambdaHook": { + "a": "alias auto_update execution_role failure_mode hook_status lambda_function logging_config stack_filters target_filters target_operations" + }, + "AWS::CloudFormation::ModuleDefaultVersion": { + "a": "arn module_name version_id" + }, + "AWS::CloudFormation::ModuleVersion": { + "a": "module_name module_package" + }, + "AWS::CloudFormation::PublicTypeVersion": { + "a": "arn log_delivery_bucket public_version_number type type_name" + }, + "AWS::CloudFormation::Publisher": { + "a": "accept_terms_and_conditions connection_arn" + }, + "AWS::CloudFormation::ResourceDefaultVersion": { + "a": "type_name type_version_arn version_id" + }, + "AWS::CloudFormation::ResourceVersion": { + "a": "execution_role_arn logging_config schema_handler_package type_name" + }, + "AWS::CloudFormation::Stack": { + "a": "capabilities description disable_rollback enable_termination_protection notification_ar_ns parameters role_arn stack_name stack_policy_body stack_policy_url stack_status_reason tags template_body template_url timeout_in_minutes", + "j": [ + "StackPolicyBody", + "TemplateBody" + ], + "m": [ + "Parameters" + ] + }, + "AWS::CloudFormation::StackSet": { + "a": "administration_role_arn auto_deployment call_as capabilities description execution_role_name managed_execution operation_preferences parameters permission_model stack_instances_group stack_set_name tags template_body template_url" + }, + "AWS::CloudFormation::TypeActivation": { + "a": "auto_update execution_role_arn logging_config major_version public_type_arn publisher_id type type_name type_name_alias version_bump" + }, + "AWS::CloudFront::CachePolicy": { + "a": "cache_policy_config" + }, + "AWS::CloudFront::CloudFrontOriginAccessIdentity": { + "a": "cloudfront_origin_access_identity_config" + }, + "AWS::CloudFront::ConnectionFunction": { + "a": "auto_publish connection_function_code connection_function_config name tags" + }, + "AWS::CloudFront::ConnectionGroup": { + "a": "anycast_ip_list_id enabled ipv_6_enabled name tags", + "x": [ + "ViewerFallback" + ] + }, + "AWS::CloudFront::ContinuousDeploymentPolicy": { + "a": "continuous_deployment_policy_config" + }, + "AWS::CloudFront::DistributionTenant": { + "a": "connection_group_id customizations distribution_id domains enabled managed_certificate_request name parameters tags", + "x": [ + "DomainMappings", + "DomainResults.ServeOn", + "DomainResults.StatusReason", + "DomainResults.StatusReasonCode", + "OnDomainTakeover" + ] + }, + "AWS::CloudFront::FieldLevelEncryptionConfig": { + "a": "caller_reference comment content_type_profile_config query_arg_profile_config" + }, + "AWS::CloudFront::FieldLevelEncryptionProfile": { + "a": "field_level_encryption_profile_config" + }, + "AWS::CloudFront::Function": { + "a": "auto_publish function_code function_config function_metadata name tags" + }, + "AWS::CloudFront::KeyGroup": { + "a": "key_group_config" + }, + "AWS::CloudFront::KeyValueStore": { + "a": "comment import_source name tags" + }, + "AWS::CloudFront::MonitoringSubscription": { + "a": "distribution_id monitoring_subscription" + }, + "AWS::CloudFront::OriginAccessControl": { + "a": "origin_access_control_config" + }, + "AWS::CloudFront::OriginRequestPolicy": { + "a": "origin_request_policy_config" + }, + "AWS::CloudFront::PublicKey": { + "a": "public_key_config" + }, + "AWS::CloudFront::RealtimeLogConfig": { + "a": "end_points fields name sampling_rate" + }, + "AWS::CloudFront::ResponseHeadersPolicy": { + "a": "response_headers_policy_config" + }, + "AWS::CloudFront::TrustStore": { + "a": "ca_certificates_bundle_source name tags use_client_certificate_ocsp_endpoint" + }, + "AWS::CloudFront::VpcOrigin": { + "a": "tags vpc_origin_endpoint_config" + }, + "AWS::CloudHSM::Cluster": { + "a": "backup_retention_policy hsm_type mode network_type subnet_ids tags", + "m": [ + "SubnetMapping" + ] + }, + "AWS::CloudTrail::Channel": { + "a": "destinations name source tags" + }, + "AWS::CloudTrail::Dashboard": { + "a": "name refresh_schedule tags termination_protection_enabled widgets", + "m": [ + "Widgets.ViewProperties" + ] + }, + "AWS::CloudTrail::EventDataStore": { + "a": "advanced_event_selectors billing_mode context_key_selectors federation_enabled federation_role_arn ingestion_enabled insight_selectors insights_destination kms_key_id max_event_size multi_region_enabled name organization_enabled retention_period tags termination_protection_enabled" + }, + "AWS::CloudTrail::ResourcePolicy": { + "a": "resource_arn resource_policy", + "j": [ + "ResourcePolicy" + ] + }, + "AWS::CloudTrail::Trail": { + "a": "advanced_event_selectors aggregation_configurations cloudwatch_logs_log_group_arn cloudwatch_logs_role_arn enable_log_file_validation event_selectors include_global_service_events insight_selectors is_logging is_multi_region_trail is_organization_trail kms_key_id s3_bucket_name s3_key_prefix sns_topic_name tags trail_name", + "x": [ + "RecursiveLogging" + ] + }, + "AWS::CloudWatch::AccessProfile": { + "a": "description name space_id tags" + }, + "AWS::CloudWatch::Alarm": { + "a": "action_configuration actions_enabled alarm_actions alarm_description alarm_name comparison_operator datapoints_to_alarm dimensions evaluate_low_sample_count_percentile evaluation_criteria evaluation_interval evaluation_periods evaluation_window extended_statistic insufficient_data_actions metric_name metrics namespace ok_actions period statistic tags threshold threshold_metric_id treat_missing_data unit warm_up_configuration", + "j": [ + "EvaluationWindow.SlidingWindow" + ] + }, + "AWS::CloudWatch::AlarmMuteRule": { + "a": "description expire_date mute_targets name rule start_date tags" + }, + "AWS::CloudWatch::Alert": { + "a": "description name notification_rules notifications_enabled profile_id rule space_id tags", + "m": [ + "NotificationRules.Target.Metadata" + ] + }, + "AWS::CloudWatch::AnomalyDetector": { + "a": "configuration dimensions metric_characteristics metric_math_anomaly_detector metric_name namespace single_metric_anomaly_detector stat" + }, + "AWS::CloudWatch::CompositeAlarm": { + "a": "action_configuration actions_enabled actions_suppressor actions_suppressor_extension_period actions_suppressor_wait_period alarm_actions alarm_description alarm_name alarm_rule insufficient_data_actions ok_actions tags" + }, + "AWS::CloudWatch::Dashboard": { + "a": "dashboard_body dashboard_name tags" + }, + "AWS::CloudWatch::Domain": { + "a": "identity_provider_configuration identity_providers name tags" + }, + "AWS::CloudWatch::DomainAccessGrantForOrganization": { + "a": "domain_id name permission principal tags" + }, + "AWS::CloudWatch::DomainForOrganization": { + "a": "domain_access_role_arn identity_provider_configuration identity_providers name tags" + }, + "AWS::CloudWatch::InsightRule": { + "a": "apply_on_transformed_logs rule_body rule_name rule_state tags" + }, + "AWS::CloudWatch::Integration": { + "a": "credential integration_attributes integration_type name role_arn tags", + "m": [ + "IntegrationAttributes" + ] + }, + "AWS::CloudWatch::LogAlarm": { + "a": "action_configuration action_log_line_count action_log_line_role_arn actions_enabled alarm_actions alarm_description alarm_name comparison_operator insufficient_data_actions ok_actions query_results_to_alarm query_results_to_evaluate scheduled_query_configuration tags threshold treat_missing_data warm_up_configuration" + }, + "AWS::CloudWatch::MetricStream": { + "a": "exclude_filters firehose_arn include_filters include_linked_accounts_metrics name output_format role_arn statistics_configurations tags", + "j": [ + "CreationDate", + "LastUpdateDate" + ] + }, + "AWS::CloudWatch::OTelEnrichment": { + "a": "exclude_filters include_filters" + }, + "AWS::CloudWatch::OmniDashboard": { + "a": "body description name space_id tags" + }, + "AWS::CloudWatch::ResourceMetricsConfiguration": { + "a": "metric_selections resource_arn" + }, + "AWS::CloudWatch::Space": { + "a": "agent_core_evaluation_role_arn data_access_role_arn domain_id encryption_configuration name tags" + }, + "AWS::CloudWatch::View": { + "a": "definition description name tags" + }, + "AWS::CodeArtifact::Domain": { + "a": "domain_name permissions_policy_document tags", + "j": [ + "PermissionsPolicyDocument" + ] + }, + "AWS::CodeArtifact::PackageGroup": { + "a": "contact_info description domain_name domain_owner origin_configuration pattern tags" + }, + "AWS::CodeArtifact::Repository": { + "a": "description domain_name external_connections permissions_policy_document repository_name tags upstreams", + "j": [ + "PermissionsPolicyDocument" + ] + }, + "AWS::CodeBuild::Fleet": { + "a": "base_capacity compute_configuration compute_type environment_type fleet_proxy_configuration fleet_service_role fleet_vpc_config image_id name overflow_behavior scaling_configuration tags" + }, + "AWS::CodeBuild::ReportGroup": { + "a": "delete_reports export_config name tags type" + }, + "AWS::CodeBuild::SourceCredential": { + "a": "auth_type server_type token username" + }, + "AWS::CodeCommit::Repository": { + "a": "code kms_key_id repository_description repository_name tags triggers" + }, + "AWS::CodeConnections::Connection": { + "a": "connection_name host_arn provider_type tags" + }, + "AWS::CodeConnections::Host": { + "a": "name provider_endpoint provider_type tags vpc_configuration" + }, + "AWS::CodeDeploy::Application": { + "a": "application_name compute_platform tags" + }, + "AWS::CodeDeploy::DeploymentConfig": { + "a": "compute_platform deployment_config_name minimum_healthy_hosts traffic_routing_config zonal_config" + }, + "AWS::CodeDeploy::DeploymentGroup": { + "a": "alarm_configuration application_name auto_rollback_configuration auto_scaling_groups blue_green_deployment_configuration deployment deployment_config_name deployment_group_name deployment_style ec_2_deployment_options ec_2_tag_filters ec_2_tag_set ecs_services load_balancer_info on_premises_instance_tag_filters on_premises_tag_set outdated_instances_strategy service_role_arn tags termination_hook_enabled trigger_configurations", + "r": { + "Ec2DeploymentOptions": "ec_2_deployment_options", + "Ec2TagFilters": "ec_2_tag_filters", + "Ec2TagSet": "ec_2_tag_set", + "Ec2TagSet.Ec2TagSetList": "ec_2_tag_set_list", + "Ec2TagSet.Ec2TagSetList.Ec2TagGroup": "ec_2_tag_group" + } + }, + "AWS::CodeGuruProfiler::ProfilingGroup": { + "a": "agent_permissions anomaly_detection_notification_configuration compute_platform profiling_group_name tags" + }, + "AWS::CodeGuruReviewer::RepositoryAssociation": { + "a": "bucket_name connection_arn name owner tags type" + }, + "AWS::CodePipeline::CustomActionType": { + "a": "category configuration_properties input_artifact_details output_artifact_details provider_name settings tags version", + "x": [ + "Provider" + ] + }, + "AWS::CodePipeline::Pipeline": { + "a": "artifact_store artifact_stores disable_inbound_stage_transitions execution_mode name pipeline_type restart_execution_on_update role_arn stages tags triggers variables", + "j": [ + "Stages.Actions.Configuration", + "Stages.BeforeEntry.Conditions.Rules.Configuration", + "Stages.OnFailure.Conditions.Rules.Configuration", + "Stages.OnSuccess.Conditions.Rules.Configuration" + ] + }, + "AWS::CodePipeline::Webhook": { + "a": "authentication authentication_configuration filters name register_with_third_party tags target_action target_pipeline target_pipeline_version" + }, + "AWS::CodeStarConnections::Connection": { + "a": "connection_name host_arn provider_type tags" + }, + "AWS::CodeStarConnections::RepositoryLink": { + "a": "connection_arn encryption_key_arn owner_id repository_name tags" + }, + "AWS::CodeStarConnections::SyncConfiguration": { + "a": "branch config_file publish_deployment_status repository_link_id resource_name role_arn sync_type trigger_resource_update_on" + }, + "AWS::CodeStarNotifications::NotificationRule": { + "a": "created_by detail_type event_type_id event_type_ids name resource status tags target_address targets", + "m": [ + "Tags" + ] + }, + "AWS::Cognito::IdentityPool": { + "a": "allow_classic_flow allow_unauthenticated_identities cognito_events cognito_identity_providers cognito_streams developer_provider_name identity_pool_name identity_pool_tags open_id_connect_provider_ar_ns push_sync saml_provider_ar_ns supported_login_providers", + "j": [ + "CognitoEvents", + "SupportedLoginProviders" + ] + }, + "AWS::Cognito::IdentityPoolPrincipalTag": { + "a": "identity_pool_id identity_provider_name principal_tags use_defaults", + "j": [ + "PrincipalTags" + ] + }, + "AWS::Cognito::IdentityPoolRoleAttachment": { + "a": "identity_pool_id role_mappings roles", + "m": [ + "RoleMappings", + "Roles" + ] + }, + "AWS::Cognito::LogDeliveryConfiguration": { + "a": "log_configurations user_pool_id" + }, + "AWS::Cognito::ManagedLoginBranding": { + "a": "assets client_id return_merged_resources settings use_cognito_provided_values user_pool_id", + "j": [ + "Settings" + ] + }, + "AWS::Cognito::Terms": { + "a": "client_id enforcement links terms_name terms_source user_pool_id", + "m": [ + "Links" + ] + }, + "AWS::Cognito::UserPoolClient": { + "a": "access_token_validity allowed_o_auth_flows allowed_o_auth_flows_user_pool_client allowed_o_auth_scopes analytics_configuration auth_session_validity callback_ur_ls client_name default_redirect_uri enable_propagate_additional_user_context_data enable_token_revocation explicit_auth_flows generate_secret id_token_validity logout_ur_ls prevent_user_existence_errors read_attributes refresh_token_rotation refresh_token_validity supported_identity_providers token_validity_units user_pool_id write_attributes" + }, + "AWS::Cognito::UserPoolDomain": { + "a": "custom_domain_config domain managed_login_version routing user_pool_id" + }, + "AWS::Cognito::UserPoolGroup": { + "a": "description group_name precedence role_arn user_pool_id" + }, + "AWS::Cognito::UserPoolIdentityProvider": { + "a": "attribute_mapping idp_identifiers provider_details provider_name provider_type user_pool_id", + "m": [ + "AttributeMapping", + "ProviderDetails" + ] + }, + "AWS::Cognito::UserPoolRegionalConfigurationAttachment": { + "a": "email_configuration lambda_config sms_configuration status user_pool_id user_pool_tags", + "m": [ + "UserPoolTags" + ] + }, + "AWS::Cognito::UserPoolReplica": { + "a": "region_name user_pool_id user_pool_tags_at_create", + "m": [ + "UserPoolTagsAtCreate" + ] + }, + "AWS::Cognito::UserPoolResourceServer": { + "a": "identifier name scopes user_pool_id" + }, + "AWS::Cognito::UserPoolRiskConfigurationAttachment": { + "a": "account_takeover_risk_configuration client_id compromised_credentials_risk_configuration risk_exception_configuration user_pool_id" + }, + "AWS::Cognito::UserPoolUICustomizationAttachment": { + "a": "client_id css user_pool_id" + }, + "AWS::Cognito::UserPoolUser": { + "a": "client_metadata desired_delivery_mediums force_alias_creation message_action user_attributes user_pool_id username validation_data", + "m": [ + "ClientMetadata" + ] + }, + "AWS::Cognito::UserPoolUserToGroupAttachment": { + "a": "group_name user_pool_id username" + }, + "AWS::Comprehend::DocumentClassifier": { + "a": "data_access_role_arn document_classifier_name input_data_config language_code mode model_kms_key_id model_policy output_data_config tags version_name volume_kms_key_id vpc_config" + }, + "AWS::Comprehend::DocumentClassifierEndpoint": { + "a": "desired_inference_units endpoint_name model_arn tags" + }, + "AWS::Comprehend::EntityRecognizer": { + "a": "data_access_role_arn input_data_config language_code model_kms_key_id model_policy recognizer_name tags version_name volume_kms_key_id vpc_config" + }, + "AWS::Comprehend::EntityRecognizerEndpoint": { + "a": "data_access_role_arn desired_inference_units endpoint_name flywheel_arn model_arn tags" + }, + "AWS::Comprehend::Flywheel": { + "a": "active_model_arn data_access_role_arn data_lake_s3_uri data_security_config flywheel_name model_type tags task_config" + }, + "AWS::ComputeOptimizer::AutomationRule": { + "a": "criteria description name organization_configuration priority recommended_action_types rule_type schedule status tags" + }, + "AWS::Config::AggregationAuthorization": { + "a": "authorized_account_id authorized_aws_region tags" + }, + "AWS::Config::ConfigRule": { + "a": "compliance config_rule_name description evaluation_modes input_parameters maximum_execution_frequency scope source", + "j": [ + "InputParameters" + ] + }, + "AWS::Config::ConfigurationAggregator": { + "a": "account_aggregation_sources configuration_aggregator_name organization_aggregation_source tags" + }, + "AWS::Config::ConfigurationRecorder": { + "a": "name recording_group recording_mode role_arn started_on_create" + }, + "AWS::Config::ConformancePack": { + "a": "conformance_pack_input_parameters conformance_pack_name delivery_s3_bucket delivery_s3_key_prefix tags template_body template_s3_uri template_ssm_document_details", + "x": [ + "Scope", + "Source", + "Type" + ] + }, + "AWS::Config::Connector": { + "a": "connector_configuration tags", + "x": [ + "ConnectorConfiguration.Gcp" + ] + }, + "AWS::Config::DeliveryChannel": { + "a": "config_snapshot_delivery_properties name s3_bucket_name s3_key_prefix s3_kms_key_arn sns_topic_arn" + }, + "AWS::Config::OrganizationConfigRule": { + "a": "excluded_accounts organization_config_rule_name organization_custom_policy_rule_metadata organization_custom_rule_metadata organization_managed_rule_metadata" + }, + "AWS::Config::OrganizationConformancePack": { + "a": "conformance_pack_input_parameters delivery_s3_bucket delivery_s3_key_prefix excluded_accounts organization_conformance_pack_name tags template_body template_s3_uri" + }, + "AWS::Config::RemediationConfiguration": { + "a": "automatic config_rule_name execution_controls maximum_automatic_attempts parameters resource_type retry_attempt_seconds target_id target_type target_version", + "j": [ + "Parameters" + ] + }, + "AWS::Config::StoredQuery": { + "a": "query_description query_expression query_name tags" + }, + "AWS::Connect::AgentStatus": { + "a": "description display_order instance_arn name reset_order_number state tags type" + }, + "AWS::Connect::ApprovedOrigin": { + "a": "instance_id origin" + }, + "AWS::Connect::ContactFlow": { + "a": "content description instance_arn name state tags type" + }, + "AWS::Connect::ContactFlowModule": { + "a": "content description external_invocation_configuration instance_arn name settings state tags" + }, + "AWS::Connect::ContactFlowModuleAlias": { + "a": "contact_flow_module_id contact_flow_module_version description name" + }, + "AWS::Connect::ContactFlowModuleVersion": { + "a": "contact_flow_module_id description" + }, + "AWS::Connect::ContactFlowVersion": { + "a": "contact_flow_id description" + }, + "AWS::Connect::DataLakeAssociation": { + "a": "data_set_id instance_id target_account_id" + }, + "AWS::Connect::DataTable": { + "a": "description instance_arn name status tags time_zone value_lock_level" + }, + "AWS::Connect::DataTableAttribute": { + "a": "data_table_arn description instance_arn name primary validation value_type" + }, + "AWS::Connect::DataTableRecord": { + "a": "data_table_arn data_table_record instance_arn" + }, + "AWS::Connect::EmailAddress": { + "a": "alias_configurations description display_name email_address instance_arn tags" + }, + "AWS::Connect::HoursOfOperation": { + "a": "child_hours_of_operations config description hours_of_operation_overrides instance_arn name parent_hours_of_operations tags time_zone" + }, + "AWS::Connect::Instance": { + "a": "attributes directory_id identity_management_type instance_alias tags" + }, + "AWS::Connect::InstanceStorageConfig": { + "a": "instance_arn kinesis_firehose_config kinesis_stream_config kinesis_video_stream_config resource_type s3_config storage_type" + }, + "AWS::Connect::IntegrationAssociation": { + "a": "instance_id integration_arn integration_type source_application_name source_application_url source_type tags" + }, + "AWS::Connect::Metric": { + "a": "description instance_arn metric_calculation name positive_trend_indicator status tags unit" + }, + "AWS::Connect::Notification": { + "a": "content expires_at instance_arn priority recipients tags" + }, + "AWS::Connect::PhoneNumber": { + "a": "country_code description prefix source_phone_number_arn tags target_arn type" + }, + "AWS::Connect::PredefinedAttribute": { + "a": "attribute_configuration instance_arn name purposes values" + }, + "AWS::Connect::Prompt": { + "a": "description instance_arn name s3_uri tags" + }, + "AWS::Connect::Queue": { + "a": "additional_email_addresses description hours_of_operation_arn instance_arn max_contacts name outbound_caller_config outbound_email_config quick_connect_arns status tags" + }, + "AWS::Connect::QuickConnect": { + "a": "description instance_arn name quick_connect_config tags" + }, + "AWS::Connect::RoutingProfile": { + "a": "agent_availability_timer default_outbound_queue_arn description instance_arn manual_assignment_queue_configs media_concurrencies name queue_configs tags" + }, + "AWS::Connect::SecurityKey": { + "a": "instance_id key" + }, + "AWS::Connect::SecurityProfile": { + "a": "allowed_access_control_hierarchy_group_id allowed_access_control_tags allowed_flow_modules applications description granular_access_control_configuration hierarchy_restricted_resources instance_arn permissions security_profile_name tag_restricted_resources tags" + }, + "AWS::Connect::TaskTemplate": { + "a": "client_token constraints contact_flow_arn defaults description fields instance_arn name self_assign_contact_flow_arn status tags", + "x": [ + "ContactHooks" + ] + }, + "AWS::Connect::TestCase": { + "a": "content description entry_point initialization_data instance_arn name status tags" + }, + "AWS::Connect::TrafficDistributionGroup": { + "a": "description instance_arn name tags" + }, + "AWS::Connect::UseCase": { + "a": "instance_id integration_association_id tags use_case_type" + }, + "AWS::Connect::User": { + "a": "after_contact_work_configs auto_accept_configs directory_user_id hierarchy_group_arn identity_info instance_arn password persistent_connection_configs phone_config phone_number_configs routing_profile_arn security_profile_arns tags user_proficiencies username voice_enhancement_configs" + }, + "AWS::Connect::UserHierarchyGroup": { + "a": "instance_arn name parent_group_arn tags" + }, + "AWS::Connect::UserHierarchyStructure": { + "a": "instance_arn user_hierarchy_structure" + }, + "AWS::Connect::View": { + "a": "actions description instance_arn name tags template", + "j": [ + "Template" + ] + }, + "AWS::Connect::ViewVersion": { + "a": "version_description view_arn view_content_sha_256" + }, + "AWS::Connect::Vocabulary": { + "a": "content instance_id language_code tags vocabulary_name" + }, + "AWS::Connect::Workspace": { + "a": "associations description instance_arn media name pages tags theme title visibility" + }, + "AWS::ConnectCampaigns::Campaign": { + "a": "connect_instance_arn dialer_config name outbound_call_config tags" + }, + "AWS::ConnectCampaignsV2::Campaign": { + "a": "channel_subtype_config communication_limits_override communication_time_config connect_campaign_flow_arn connect_instance_id entry_limits_config name schedule source tags type", + "j": [ + "ChannelSubtypeConfig.Email.OutboundMode.AgentlessConfig", + "ChannelSubtypeConfig.Sms.OutboundMode.AgentlessConfig", + "ChannelSubtypeConfig.Telephony.OutboundMode.AgentlessConfig", + "ChannelSubtypeConfig.WhatsApp.OutboundMode.AgentlessConfig" + ] + }, + "AWS::ControlTower::EnabledControl": { + "a": "control_identifier target_identifier", + "x": [ + "Parameters", + "Tags" + ] + }, + "AWS::ControlTower::LandingZone": { + "a": "manifest remediation_types tags version" + }, + "AWS::CustomerProfiles::CalculatedAttributeDefinition": { + "a": "attribute_details calculated_attribute_name conditions description display_name domain_name filter statistic tags use_historical_data", + "m": [ + "Filter.Groups.Dimensions.Attributes" + ] + }, + "AWS::CustomerProfiles::Domain": { + "a": "dead_letter_queue_url default_encryption_key default_expiration_days domain_name tags", + "x": [ + "DataStore", + "Matching", + "RuleBasedMatching", + "Stats" + ] + }, + "AWS::CustomerProfiles::DomainObjectType": { + "a": "description domain_name encryption_key fields object_type_name tags", + "m": [ + "Fields" + ] + }, + "AWS::CustomerProfiles::EventStream": { + "a": "domain_name event_stream_name tags uri" + }, + "AWS::CustomerProfiles::EventTrigger": { + "a": "description domain_name event_trigger_conditions event_trigger_limits event_trigger_name intent_filter_definition object_type_name segment_filter tags" + }, + "AWS::CustomerProfiles::Integration": { + "a": "domain_name event_trigger_names flow_definition object_type_name object_type_names scope tags uri" + }, + "AWS::CustomerProfiles::ObjectType": { + "a": "allow_profile_creation description domain_name encryption_key expiration_days fields keys max_profile_object_count object_type_name source_last_updated_timestamp_format source_priority tags template_id" + }, + "AWS::CustomerProfiles::Recommender": { + "a": "description domain_name recommender_config recommender_name recommender_recipe_name tags" + }, + "AWS::CustomerProfiles::RecommenderFilter": { + "a": "description domain_name recommender_filter_expression recommender_filter_name recommender_schema_name tags" + }, + "AWS::CustomerProfiles::SegmentDefinition": { + "a": "description display_name domain_name segment_definition_name segment_groups segment_sort segment_sql_query tags" + }, + "AWS::DAX::Cluster": { + "a": "availability_zones cluster_endpoint_encryption_type cluster_name description iam_role_arn network_type node_type notification_topic_arn parameter_group_name preferred_maintenance_window replication_factor security_group_ids sse_specification subnet_group_name tags", + "j": [ + "Tags" + ] + }, + "AWS::DAX::ParameterGroup": { + "a": "description parameter_group_name parameter_name_values", + "j": [ + "ParameterNameValues" + ] + }, + "AWS::DAX::SubnetGroup": { + "a": "description subnet_group_name subnet_ids" + }, + "AWS::DLM::LifecyclePolicy": { + "a": "copy_tags create_interval cross_region_copy_targets default_policy description exclusions execution_role_arn extend_deletion policy_details retain_interval state tags" + }, + "AWS::DMS::Certificate": { + "a": "certificate_identifier certificate_pem certificate_wallet" + }, + "AWS::DMS::DataMigration": { + "a": "data_migration_identifier data_migration_name data_migration_settings data_migration_type migration_project_identifier service_access_role_arn source_data_settings tags" + }, + "AWS::DMS::DataProvider": { + "a": "data_provider_identifier data_provider_name description engine exact_settings settings tags virtual", + "x": [ + "Settings.OracleSettings.S3AccessRoleArn", + "Settings.OracleSettings.S3Path" + ] + }, + "AWS::DMS::Endpoint": { + "a": "certificate_arn database_name doc_db_settings dynamo_db_settings elasticsearch_settings endpoint_identifier endpoint_type engine_name extra_connection_attributes gcp_my_sql_settings ibm_db_2_settings kafka_settings kinesis_settings kms_key_id microsoft_sql_server_settings mongo_db_settings my_sql_settings neptune_settings oracle_settings password port postgre_sql_settings redis_settings redshift_settings resource_identifier s3_settings server_name ssl_mode sybase_settings tags username" + }, + "AWS::DMS::EventSubscription": { + "a": "enabled event_categories sns_topic_arn source_ids source_type subscription_name tags" + }, + "AWS::DMS::InstanceProfile": { + "a": "availability_zone description instance_profile_identifier instance_profile_name kms_key_arn network_type publicly_accessible subnet_group_identifier tags vpc_security_groups" + }, + "AWS::DMS::MigrationProject": { + "a": "description instance_profile_identifier migration_project_identifier migration_project_name schema_conversion_application_attributes source_data_provider_descriptors tags target_data_provider_descriptors transformation_rules" + }, + "AWS::DMS::ReplicationConfig": { + "a": "compute_config replication_config_identifier replication_settings replication_type resource_identifier source_endpoint_arn supplemental_settings table_mappings tags target_endpoint_arn", + "j": [ + "ReplicationSettings", + "SupplementalSettings", + "TableMappings" + ] + }, + "AWS::DMS::ReplicationSubnetGroup": { + "a": "replication_subnet_group_description replication_subnet_group_identifier subnet_ids tags" + }, + "AWS::DMS::ReplicationTask": { + "a": "cdc_start_position cdc_start_time cdc_stop_position migration_type replication_instance_arn replication_task_identifier replication_task_settings resource_identifier source_endpoint_arn table_mappings tags target_endpoint_arn task_data" + }, + "AWS::DRS::LaunchConfigurationTemplate": { + "a": "copy_private_ip copy_tags export_bucket_arn launch_disposition launch_into_source_instance licensing post_launch_enabled tags target_instance_type_right_sizing_method" + }, + "AWS::DRS::RecoveryPlan": { + "a": "description name tags" + }, + "AWS::DRS::ReplicationConfigurationTemplate": { + "a": "associate_default_security_group auto_replicate_new_disks bandwidth_throttling create_public_ip data_plane_routing default_large_staging_disk_type ebs_encryption ebs_encryption_key_arn internet_protocol pit_policy replication_server_instance_type replication_servers_security_groups_i_ds staging_area_subnet_id staging_area_tags tags use_dedicated_replication_server", + "m": [ + "StagingAreaTags" + ] + }, + "AWS::DRS::SourceNetwork": { + "a": "origin_account_id origin_region tags vpc_id" + }, + "AWS::DSQL::Cluster": { + "a": "deletion_protection_enabled kms_encryption_key multi_region_properties policy_document tags", + "x": [ + "MetricGroups" + ] + }, + "AWS::DataBrew::Dataset": { + "a": "format format_options input name path_options source tags" + }, + "AWS::DataBrew::Job": { + "a": "data_catalog_outputs database_outputs dataset_name encryption_key_arn encryption_mode job_sample log_subscription max_capacity max_retries name output_location outputs profile_configuration project_name recipe role_arn tags timeout type validation_configurations", + "m": [ + "ProfileConfiguration.ColumnStatisticsConfigurations.Statistics.Overrides.Parameters", + "ProfileConfiguration.DatasetStatisticsConfiguration.Overrides.Parameters" + ] + }, + "AWS::DataBrew::Project": { + "a": "dataset_name name recipe_name role_arn sample tags" + }, + "AWS::DataBrew::Ruleset": { + "a": "description name rules tags target_arn" + }, + "AWS::DataBrew::Schedule": { + "a": "cron_expression job_names name tags" + }, + "AWS::DataExchange::DataSet": { + "a": "asset_type description name tags" + }, + "AWS::DataExchange::EventAction": { + "a": "action event tags" + }, + "AWS::DataPipeline::Pipeline": { + "a": "activate description name parameter_objects parameter_values pipeline_objects pipeline_tags" + }, + "AWS::DataSync::Agent": { + "a": "activation_key agent_name security_group_arns subnet_arns tags vpc_endpoint_id" + }, + "AWS::DataSync::LocationAzureBlob": { + "a": "agent_arns azure_access_tier azure_blob_authentication_type azure_blob_container_url azure_blob_sas_configuration azure_blob_type cmk_secret_config custom_secret_config federated_identity subdirectory tags" + }, + "AWS::DataSync::LocationEFS": { + "a": "access_point_arn ec_2_config efs_filesystem_arn file_system_access_role_arn in_transit_encryption subdirectory tags", + "r": { + "Ec2Config": "ec_2_config" + } + }, + "AWS::DataSync::LocationFSxLustre": { + "a": "fsx_filesystem_arn security_group_arns subdirectory tags" + }, + "AWS::DataSync::LocationFSxONTAP": { + "a": "protocol security_group_arns storage_virtual_machine_arn subdirectory tags" + }, + "AWS::DataSync::LocationFSxOpenZFS": { + "a": "fsx_filesystem_arn protocol security_group_arns subdirectory tags" + }, + "AWS::DataSync::LocationFSxWindows": { + "a": "cmk_secret_config custom_secret_config domain fsx_filesystem_arn password security_group_arns subdirectory tags user" + }, + "AWS::DataSync::LocationHDFS": { + "a": "agent_arns authentication_type block_size cmk_secret_config custom_secret_config kerberos_keytab kerberos_krb_5_conf kerberos_principal kms_key_provider_uri name_nodes qop_configuration replication_factor simple_user subdirectory tags" + }, + "AWS::DataSync::LocationNFS": { + "a": "mount_options on_prem_config server_hostname subdirectory tags" + }, + "AWS::DataSync::LocationObjectStorage": { + "a": "access_key agent_arns bucket_name cmk_secret_config custom_secret_config federated_identity secret_key server_certificate server_hostname server_port server_protocol subdirectory tags" + }, + "AWS::DataSync::LocationS3": { + "a": "s3_bucket_arn s3_config s3_storage_class subdirectory tags" + }, + "AWS::DataSync::LocationSMB": { + "a": "agent_arns authentication_type cmk_secret_config custom_secret_config dns_ip_addresses domain kerberos_keytab kerberos_krb_5_conf kerberos_principal mount_options password server_hostname subdirectory tags user" + }, + "AWS::DataSync::Task": { + "a": "cloudwatch_log_group_arn destination_location_arn excludes includes manifest_config name options schedule source_location_arn tags task_mode task_report_config" + }, + "AWS::DataZone::Connection": { + "a": "aws_location configurations description domain_identifier enable_trusted_identity_propagation environment_identifier name project_identifier props scope", + "m": [ + "Configurations.Properties" + ] + }, + "AWS::DataZone::DataSource": { + "a": "asset_forms_input configuration connection_identifier description domain_identifier enable_setting environment_identifier name project_identifier publish_on_import recommendation schedule type" + }, + "AWS::DataZone::Domain": { + "a": "description domain_execution_role domain_version kms_key_identifier name service_role single_sign_on tags" + }, + "AWS::DataZone::DomainUnit": { + "a": "description domain_identifier name parent_domain_unit_identifier" + }, + "AWS::DataZone::Environment": { + "a": "deployment_order description domain_identifier environment_account_identifier environment_account_region environment_blueprint_identifier environment_configuration_id environment_profile_identifier environment_role_arn glossary_terms name project_identifier user_parameters", + "x": [ + "Provider" + ] + }, + "AWS::DataZone::EnvironmentActions": { + "a": "description domain_identifier environment_identifier identifier name parameters" + }, + "AWS::DataZone::EnvironmentBlueprintConfiguration": { + "a": "domain_identifier enabled_regions environment_blueprint_identifier environment_role_permission_boundary global_parameters manage_access_role_arn provisioning_configurations provisioning_role_arn regional_parameters", + "m": [ + "GlobalParameters", + "RegionalParameters.Parameters" + ] + }, + "AWS::DataZone::EnvironmentProfile": { + "a": "aws_account_id aws_account_region description domain_identifier environment_blueprint_identifier name project_identifier user_parameters" + }, + "AWS::DataZone::FormType": { + "a": "description domain_identifier model name owning_project_identifier status" + }, + "AWS::DataZone::GroupProfile": { + "a": "domain_identifier group_identifier group_type role_principal_arn status" + }, + "AWS::DataZone::Owner": { + "a": "domain_identifier entity_identifier entity_type owner" + }, + "AWS::DataZone::PolicyGrant": { + "a": "detail domain_identifier entity_identifier entity_type policy_type principal" + }, + "AWS::DataZone::Project": { + "a": "description domain_identifier domain_unit_id glossary_terms membership_assignments name project_category project_execution_role project_profile_id project_profile_version resource_tags user_parameters" + }, + "AWS::DataZone::ProjectMembership": { + "a": "designation domain_identifier member project_identifier" + }, + "AWS::DataZone::ProjectProfile": { + "a": "allow_custom_project_resource_tags description domain_identifier domain_unit_identifier environment_configurations name project_resource_tags project_resource_tags_description status use_default_configurations" + }, + "AWS::DataZone::SubscriptionTarget": { + "a": "applicable_asset_types authorized_principals domain_identifier environment_identifier manage_access_role name provider_name subscription_target_config type", + "x": [ + "Provider" + ] + }, + "AWS::DataZone::UserProfile": { + "a": "domain_identifier session_name status user_identifier user_type" + }, + "AWS::Deadline::Budget": { + "a": "actions approximate_dollar_limit description display_name farm_id schedule tags usage_tracking_resource" + }, + "AWS::Deadline::Farm": { + "a": "cost_scale_factor description display_name kms_key_arn tags" + }, + "AWS::Deadline::Fleet": { + "a": "configuration description display_name farm_id host_configuration max_worker_count min_worker_count role_arn tags" + }, + "AWS::Deadline::LicenseEndpoint": { + "a": "security_group_ids subnet_ids tags vpc_id" + }, + "AWS::Deadline::Limit": { + "a": "amount_requirement_name description display_name farm_id max_count" + }, + "AWS::Deadline::MeteredProduct": { + "a": "license_endpoint_id product_id" + }, + "AWS::Deadline::Monitor": { + "a": "display_name identity_center_instance_arn identity_center_region role_arn subdomain tags" + }, + "AWS::Deadline::Queue": { + "a": "allowed_storage_profile_ids default_budget_action description display_name farm_id job_attachment_settings job_run_as_user required_file_system_location_names role_arn scheduling_configuration tags" + }, + "AWS::Deadline::QueueEnvironment": { + "a": "farm_id priority queue_id template template_type" + }, + "AWS::Deadline::QueueFleetAssociation": { + "a": "farm_id fleet_id queue_id" + }, + "AWS::Deadline::QueueLimitAssociation": { + "a": "farm_id limit_id queue_id" + }, + "AWS::Deadline::StorageProfile": { + "a": "display_name farm_id file_system_locations os_family" + }, + "AWS::Deadline::Worker": { + "a": "farm_id fleet_id host_properties tags" + }, + "AWS::Detective::Graph": { + "a": "auto_enable_members tags" + }, + "AWS::Detective::MemberInvitation": { + "a": "disable_email_notification graph_arn member_email_address member_id message" + }, + "AWS::Detective::OrganizationAdmin": { + "a": "account_id" + }, + "AWS::DevOpsAgent::AgentSpace": { + "a": "description kms_key_arn locale name operator_app preferences tags" + }, + "AWS::DevOpsAgent::Asset": { + "a": "agent_space_id asset_type files metadata zip", + "j": [ + "Files.Metadata", + "Metadata" + ] + }, + "AWS::DevOpsAgent::Association": { + "a": "agent_space_id configuration linked_association_ids service_id", + "x": [ + "Capabilities" + ] + }, + "AWS::DevOpsAgent::PrivateConnection": { + "a": "certificate connection_configuration name tags" + }, + "AWS::DevOpsAgent::Service": { + "a": "exchange_url_private_connection_name kms_key_arn name private_connection_name service_details service_type tags target_url_private_connection_name" + }, + "AWS::DevOpsAgent::Trigger": { + "a": "action agent_space_id condition status type", + "j": [ + "Action" + ] + }, + "AWS::DevOpsGuru::LogAnomalyDetectionIntegration": {}, + "AWS::DevOpsGuru::NotificationChannel": { + "a": "config" + }, + "AWS::DevOpsGuru::ResourceCollection": { + "a": "resource_collection_filter" + }, + "AWS::DirectConnect::Connection": { + "a": "bandwidth connection_name lag_id location provider_name request_mac_sec tags", + "j": [ + "LagId" + ] + }, + "AWS::DirectConnect::DirectConnectGateway": { + "a": "amazon_side_asn direct_connect_gateway_name tags" + }, + "AWS::DirectConnect::DirectConnectGatewayAssociation": { + "a": "accept_direct_connect_gateway_association_proposal_role_arn allowed_prefixes_to_direct_connect_gateway associated_gateway_id direct_connect_gateway_id", + "j": [ + "AssociatedGatewayId", + "DirectConnectGatewayId" + ] + }, + "AWS::DirectConnect::Lag": { + "a": "connections_bandwidth lag_name location minimum_links provider_name request_mac_sec tags" + }, + "AWS::DirectConnect::PrivateVirtualInterface": { + "a": "allocate_private_virtual_interface_role_arn bgp_peers connection_id direct_connect_gateway_id enable_site_link mtu rate_limit tags virtual_gateway_id virtual_interface_name vlan", + "j": [ + "ConnectionId", + "DirectConnectGatewayId" + ] + }, + "AWS::DirectConnect::PublicVirtualInterface": { + "a": "allocate_public_virtual_interface_role_arn bgp_peers connection_id rate_limit route_filter_prefixes tags virtual_interface_name vlan", + "j": [ + "ConnectionId" + ] + }, + "AWS::DirectConnect::ResiliencyGroup": { + "a": "connection_arns intended_resiliency_model resiliency_group_name tags" + }, + "AWS::DirectConnect::TransitVirtualInterface": { + "a": "allocate_transit_virtual_interface_role_arn bgp_peers connection_id direct_connect_gateway_id enable_site_link mtu rate_limit tags virtual_interface_name vlan", + "j": [ + "ConnectionId", + "DirectConnectGatewayId" + ] + }, + "AWS::DirectoryService::MicrosoftAD": { + "a": "create_alias edition enable_sso name password short_name vpc_settings" + }, + "AWS::DirectoryService::SimpleAD": { + "a": "create_alias description enable_sso name password short_name size tags vpc_settings" + }, + "AWS::DocDB::DBClusterParameterGroup": { + "a": "description family name parameters tags", + "j": [ + "Parameters" + ] + }, + "AWS::DocDB::DBSubnetGroup": { + "a": "db_subnet_group_description db_subnet_group_name subnet_ids tags" + }, + "AWS::DocDB::EventSubscription": { + "a": "enabled event_categories sns_topic_arn source_ids source_type subscription_name" + }, + "AWS::DocDB::GlobalCluster": { + "a": "deletion_protection engine engine_version global_cluster_identifier source_db_cluster_identifier storage_encrypted tags", + "j": [ + "SourceDBClusterIdentifier" + ] + }, + "AWS::DocDBElastic::Cluster": { + "a": "admin_user_name admin_user_password auth_type backup_retention_period cluster_name kms_key_id preferred_backup_window preferred_maintenance_window shard_capacity shard_count shard_instance_count subnet_ids tags vpc_security_group_ids" + }, + "AWS::DocDBElastic::ClusterSnapshot": { + "a": "cluster_arn snapshot_name tags" + }, + "AWS::DynamoDB::GlobalTable": { + "a": "attribute_definitions billing_mode global_secondary_indexes global_table_source_arn global_table_witnesses key_schema local_secondary_indexes multi_region_consistency read_on_demand_throughput_settings read_provisioned_throughput_settings replicas sse_specification stream_specification table_name table_type time_to_live_specification vector_indexes warm_throughput write_on_demand_throughput_settings write_provisioned_throughput_settings", + "j": [ + "Replicas.ReplicaStreamSpecification.ResourcePolicy.PolicyDocument", + "Replicas.ResourcePolicy.PolicyDocument", + "Replicas.SSESpecification.KMSMasterKeyId" + ] + }, + "AWS::DynamoDB::Table": { + "a": "attribute_definitions billing_mode contributor_insights_specification deletion_protection_enabled global_secondary_indexes import_source_specification key_schema kinesis_stream_specification local_secondary_indexes on_demand_throughput point_in_time_recovery_specification provisioned_throughput resource_policy sse_specification stream_specification table_class table_name tags time_to_live_specification vector_indexes warm_throughput", + "j": [ + "KeySchema", + "ResourcePolicy.PolicyDocument", + "SSESpecification.KMSMasterKeyId", + "StreamSpecification.ResourcePolicy.PolicyDocument" + ] + }, + "AWS::EC2::ApplicationStatusCheck": { + "a": "aggregation device_index failure_threshold health_check_paths initialization_grace_period_seconds interval ip_scope ip_version path port protocol status_code_matcher success_threshold tags timeout" + }, + "AWS::EC2::CapacityManagerDataExport": { + "a": "output_format s3_bucket_name s3_bucket_prefix schedule tags" + }, + "AWS::EC2::CapacityReservation": { + "a": "availability_zone availability_zone_id ebs_optimized end_date end_date_type ephemeral_storage instance_count instance_match_criteria instance_platform instance_type out_post_arn placement_group_arn tag_specifications tenancy unused_reservation_billing_owner_id" + }, + "AWS::EC2::CapacityReservationFleet": { + "a": "allocation_strategy end_date instance_match_criteria instance_type_specifications no_remove_end_date remove_end_date tag_specifications tenancy total_target_capacity" + }, + "AWS::EC2::CarrierGateway": { + "a": "tags vpc_id" + }, + "AWS::EC2::ClientVpnAuthorizationRule": { + "a": "access_group_id authorize_all_groups client_vpn_endpoint_id description target_network_cidr" + }, + "AWS::EC2::ClientVpnEndpoint": { + "a": "authentication_options authorization_policy client_cidr_block client_connect_options client_login_banner_options client_route_enforcement_options connection_log_options description device_posture_options disconnect_on_session_timeout dns_servers endpoint_ip_address_type security_group_ids self_service_portal server_certificate_arn session_timeout_hours split_tunnel tag_specifications traffic_ip_address_type transit_gateway_configuration transport_protocol vpc_id vpn_port" + }, + "AWS::EC2::ClientVpnRoute": { + "a": "client_vpn_endpoint_id description destination_cidr_block target_vpc_subnet_id" + }, + "AWS::EC2::ClientVpnTargetNetworkAssociation": { + "a": "availability_zone availability_zone_id client_vpn_endpoint_id subnet_id" + }, + "AWS::EC2::CustomerGateway": { + "a": "bgp_asn bgp_asn_extended certificate_arn device_name ip_address tags type" + }, + "AWS::EC2::DHCPOptions": { + "a": "domain_name domain_name_servers ipv_6_address_preferred_lease_time netbios_name_servers netbios_node_type ntp_servers tags" + }, + "AWS::EC2::EC2Fleet": { + "a": "context excess_capacity_termination_policy launch_template_configs on_demand_options replace_unhealthy_instances reserved_capacity_options spot_options tag_specifications target_capacity_specification terminate_instances_with_expiration type valid_from valid_until" + }, + "AWS::EC2::EIP": { + "a": "address domain instance_id ipam_pool_id network_border_group public_ipv_4_pool tags transfer_address" + }, + "AWS::EC2::EIPAssociation": { + "a": "allocation_id eip instance_id network_interface_id private_ip_address", + "j": [ + "EIP" + ] + }, + "AWS::EC2::EgressOnlyInternetGateway": { + "a": "tags vpc_id" + }, + "AWS::EC2::EnclaveCertificateIamRoleAssociation": { + "a": "certificate_arn role_arn" + }, + "AWS::EC2::FlowLog": { + "a": "deliver_cross_account_role deliver_logs_permission_arn destination_options log_destination log_destination_type log_format log_group_name max_aggregation_interval resource_id resource_type tag_field_specifications tags traffic_type" + }, + "AWS::EC2::FpgaImage": { + "a": "description input_storage_location logs_storage_location name tags" + }, + "AWS::EC2::GatewayRouteTableAssociation": { + "a": "gateway_id route_table_id" + }, + "AWS::EC2::Host": { + "a": "asset_id auto_placement availability_zone host_maintenance host_recovery instance_family instance_type outpost_arn tags" + }, + "AWS::EC2::IPAM": { + "a": "default_resource_discovery_organizational_unit_exclusions description enable_private_gua metered_account operating_regions tags tier" + }, + "AWS::EC2::IPAMAllocation": { + "a": "cidr description ipam_pool_id netmask_length" + }, + "AWS::EC2::IPAMPool": { + "a": "address_family allocation_default_netmask_length allocation_max_netmask_length allocation_min_netmask_length allocation_resource_tags auto_import aws_service description ipam_scope_id locale provisioned_cidrs public_ip_source publicly_advertisable source_ipam_pool_id source_resource tags" + }, + "AWS::EC2::IPAMPoolCidr": { + "a": "cidr ipam_pool_id netmask_length" + }, + "AWS::EC2::IPAMPrefixListResolver": { + "a": "address_family description ipam_id rules tags" + }, + "AWS::EC2::IPAMPrefixListResolverTarget": { + "a": "desired_version ipam_prefix_list_resolver_id prefix_list_id prefix_list_region tags track_latest_version" + }, + "AWS::EC2::IPAMResourceDiscovery": { + "a": "description operating_regions organizational_unit_exclusions tags" + }, + "AWS::EC2::IPAMResourceDiscoveryAssociation": { + "a": "ipam_id ipam_resource_discovery_id tags" + }, + "AWS::EC2::IPAMScope": { + "a": "description external_authority_configuration ipam_id tags" + }, + "AWS::EC2::IPv4Pool": { + "a": "tags" + }, + "AWS::EC2::Instance": { + "a": "additional_info affinity availability_zone block_device_mappings cpu_options credit_specification disable_api_termination ebs_optimized elastic_gpu_specifications elastic_inference_accelerators enclave_options hibernation_options host_id host_resource_group_arn iam_instance_profile image_id instance_initiated_shutdown_behavior instance_type ipv_6_address_count ipv_6_addresses kernel_id key_name launch_template license_specifications metadata_options monitoring network_interfaces placement_group_name private_dns_name_options private_ip_address propagate_tags_to_volume_on_creation ramdisk_id security_group_ids security_groups source_dest_check ssm_associations subnet_id tags tenancy user_data volumes", + "j": [ + "BlockDeviceMappings.NoDevice" + ] + }, + "AWS::EC2::InstanceConnectEndpoint": { + "a": "client_token preserve_client_ip security_group_ids subnet_id tags" + }, + "AWS::EC2::InstanceEventWindow": { + "a": "cron_expression name tags time_ranges" + }, + "AWS::EC2::InternetGateway": { + "a": "tags" + }, + "AWS::EC2::IpPoolRouteTableAssociation": { + "a": "public_ipv_4_pool route_table_id" + }, + "AWS::EC2::IpamExternalResourceVerificationToken": { + "a": "ipam_id tags" + }, + "AWS::EC2::IpamInternetRegistryAssociation": { + "a": "description ipam_id organization_handle rir tags" + }, + "AWS::EC2::KeyPair": { + "a": "key_format key_name key_type public_key_material tags" + }, + "AWS::EC2::LaunchTemplate": { + "a": "launch_template_data launch_template_name tag_specifications version_description", + "x": [ + "LaunchTemplateData.BlockDeviceMappings.Ebs.EbsCardIndex", + "LaunchTemplateData.BlockDeviceMappings.Ebs.VolumeInitializationRate", + "LaunchTemplateData.CpuOptions.NestedVirtualization", + "LaunchTemplateData.NetworkInterfaces.EnaQueueCount", + "LaunchTemplateData.NetworkPerformanceOptions" + ] + }, + "AWS::EC2::LocalGatewayRoute": { + "a": "destination_cidr_block local_gateway_route_table_id local_gateway_virtual_interface_group_id network_interface_id" + }, + "AWS::EC2::LocalGatewayRouteTable": { + "a": "local_gateway_id mode tags" + }, + "AWS::EC2::LocalGatewayRouteTableVPCAssociation": { + "a": "local_gateway_route_table_id tags vpc_id" + }, + "AWS::EC2::LocalGatewayRouteTableVirtualInterfaceGroupAssociation": { + "a": "local_gateway_route_table_id local_gateway_virtual_interface_group_id tags" + }, + "AWS::EC2::LocalGatewayVirtualInterface": { + "a": "local_address local_gateway_virtual_interface_group_id outpost_lag_id peer_address peer_bgp_asn peer_bgp_asn_extended tags vlan" + }, + "AWS::EC2::LocalGatewayVirtualInterfaceGroup": { + "a": "local_bgp_asn local_bgp_asn_extended local_gateway_id tags" + }, + "AWS::EC2::NatGateway": { + "a": "allocation_id availability_mode availability_zone_addresses connectivity_type max_drain_duration_seconds private_ip_address secondary_allocation_ids secondary_private_ip_address_count secondary_private_ip_addresses subnet_id tags vpc_id" + }, + "AWS::EC2::NetworkAcl": { + "a": "tags vpc_id" + }, + "AWS::EC2::NetworkInsightsAccessScope": { + "a": "exclude_paths match_paths tags" + }, + "AWS::EC2::NetworkInsightsAccessScopeAnalysis": { + "a": "network_insights_access_scope_id tags" + }, + "AWS::EC2::NetworkInsightsAnalysis": { + "a": "filter_in_arns network_insights_path_id tags", + "x": [ + "AdditionalAccounts", + "Explanations.ComponentAccount", + "Explanations.ComponentRegion", + "Explanations.RouteTableRoute.State", + "Explanations.TransitGateway", + "Explanations.TransitGatewayAttachment", + "Explanations.TransitGatewayPolicyTable", + "Explanations.TransitGatewayPolicyTableEntry", + "Explanations.TransitGatewayRouteTable", + "Explanations.TransitGatewayRouteTableRoute", + "FilterOutArns", + "ForwardPathComponents.AdditionalDetails", + "ForwardPathComponents.ElasticLoadBalancerListener", + "ForwardPathComponents.Explanations", + "ForwardPathComponents.RouteTableRoute.State", + "ForwardPathComponents.ServiceName", + "ForwardPathComponents.TransitGateway", + "ForwardPathComponents.TransitGatewayPolicyTableEntry", + "ForwardPathComponents.TransitGatewayRouteTableRoute", + "ReturnPathComponents.AdditionalDetails", + "ReturnPathComponents.ElasticLoadBalancerListener", + "ReturnPathComponents.Explanations", + "ReturnPathComponents.RouteTableRoute.State", + "ReturnPathComponents.ServiceName", + "ReturnPathComponents.TransitGateway", + "ReturnPathComponents.TransitGatewayPolicyTableEntry", + "ReturnPathComponents.TransitGatewayRouteTableRoute", + "SuggestedAccounts" + ] + }, + "AWS::EC2::NetworkInsightsPath": { + "a": "destination destination_ip destination_port filter_at_destination filter_at_source protocol source source_ip tags" + }, + "AWS::EC2::NetworkInterface": { + "a": "connection_tracking_specification description enable_primary_ipv_6 group_set interface_type ipv_4_prefix_count ipv_4_prefixes ipv_6_address_count ipv_6_addresses ipv_6_prefix_count ipv_6_prefixes private_ip_address private_ip_addresses public_ip_dns_hostname_type_specification secondary_private_ip_address_count source_dest_check subnet_id tags" + }, + "AWS::EC2::NetworkInterfaceAttachment": { + "a": "delete_on_termination device_index ena_queue_count ena_srd_specification instance_id network_interface_id" + }, + "AWS::EC2::NetworkPerformanceMetricSubscription": { + "a": "destination metric source statistic" + }, + "AWS::EC2::PlacementGroup": { + "a": "parent_group_id partition_count spread_level strategy tags" + }, + "AWS::EC2::PrefixList": { + "a": "address_family entries max_entries prefix_list_name tags" + }, + "AWS::EC2::Route": { + "a": "carrier_gateway_id core_network_arn destination_cidr_block destination_ipv_6_cidr_block destination_prefix_list_id egress_only_internet_gateway_id gateway_id instance_id local_gateway_id nat_gateway_id network_interface_id odb_network_arn route_table_id transit_gateway_id vpc_endpoint_id vpc_peering_connection_id" + }, + "AWS::EC2::RouteServer": { + "a": "amazon_side_asn persist_routes persist_routes_duration sns_notifications_enabled tags" + }, + "AWS::EC2::RouteServerAssociation": { + "a": "route_server_id vpc_id" + }, + "AWS::EC2::RouteServerEndpoint": { + "a": "route_server_id subnet_id tags" + }, + "AWS::EC2::RouteServerPeer": { + "a": "bgp_options peer_address route_server_endpoint_id tags" + }, + "AWS::EC2::RouteServerPropagation": { + "a": "route_server_id route_table_id" + }, + "AWS::EC2::RouteTable": { + "a": "tags vpc_id" + }, + "AWS::EC2::SecondaryNetwork": { + "a": "ipv_4_cidr_block network_type tags" + }, + "AWS::EC2::SecurityGroup": { + "a": "group_description group_name security_group_egress security_group_ingress tags vpc_id" + }, + "AWS::EC2::SecurityGroupEgress": { + "a": "cidr_ip cidr_ipv_6 description destination_prefix_list_id destination_security_group_id from_port group_id ip_protocol to_port" + }, + "AWS::EC2::SecurityGroupIngress": { + "a": "cidr_ip cidr_ipv_6 description from_port group_id group_name ip_protocol source_prefix_list_id source_security_group_id source_security_group_name source_security_group_owner_id to_port" + }, + "AWS::EC2::SecurityGroupVpcAssociation": { + "a": "group_id vpc_id" + }, + "AWS::EC2::Snapshot": { + "a": "description tags volume_id" + }, + "AWS::EC2::SnapshotBlockPublicAccess": { + "a": "state" + }, + "AWS::EC2::SpotFleet": { + "a": "spot_fleet_request_config_data tags" + }, + "AWS::EC2::SqlHaStandbyDetectedInstance": { + "a": "instance_id sql_server_credentials" + }, + "AWS::EC2::Subnet": { + "a": "assign_ipv_6_address_on_creation availability_zone availability_zone_id cidr_block enable_dns_64 enable_lni_at_device_index ipv_4_ipam_pool_id ipv_4_netmask_length ipv_6_cidr_block ipv_6_ipam_pool_id ipv_6_native ipv_6_netmask_length map_public_ip_on_launch outpost_arn private_dns_name_options_on_launch tags vpc_id" + }, + "AWS::EC2::SubnetCidrBlock": { + "a": "ipv_6_cidr_block ipv_6_ipam_pool_id ipv_6_netmask_length subnet_id" + }, + "AWS::EC2::SubnetCidrReservation": { + "a": "cidr description reservation_type subnet_id tags" + }, + "AWS::EC2::SubnetNetworkAclAssociation": { + "a": "network_acl_id subnet_id" + }, + "AWS::EC2::SubnetRouteTableAssociation": { + "a": "route_table_id subnet_id" + }, + "AWS::EC2::TrafficMirrorFilter": { + "a": "description network_services tags" + }, + "AWS::EC2::TrafficMirrorFilterRule": { + "a": "description destination_cidr_block destination_port_range protocol rule_action rule_number source_cidr_block source_port_range tags traffic_direction traffic_mirror_filter_id" + }, + "AWS::EC2::TrafficMirrorSession": { + "a": "description network_interface_id owner_id packet_length session_number tags traffic_mirror_filter_id traffic_mirror_target_id virtual_network_id" + }, + "AWS::EC2::TrafficMirrorTarget": { + "a": "description gateway_load_balancer_endpoint_id network_interface_id network_load_balancer_arn tags" + }, + "AWS::EC2::TransitGateway": { + "a": "amazon_side_asn association_default_route_table_id auto_accept_shared_attachments default_route_table_association default_route_table_propagation description dns_support encryption_support multicast_support propagation_default_route_table_id security_group_referencing_support tags transit_gateway_cidr_blocks vpn_ecmp_support" + }, + "AWS::EC2::TransitGatewayAttachment": { + "a": "options subnet_ids tags transit_gateway_id vpc_id" + }, + "AWS::EC2::TransitGatewayAttachmentNatConfiguration": { + "a": "nat_gateway_rules nat_gateway_support nat_system_route_support transit_gateway_attachment_id" + }, + "AWS::EC2::TransitGatewayConnect": { + "a": "options tags transport_transit_gateway_attachment_id" + }, + "AWS::EC2::TransitGatewayConnectPeer": { + "a": "connect_peer_configuration tags transit_gateway_attachment_id" + }, + "AWS::EC2::TransitGatewayMeteringPolicy": { + "a": "middlebox_attachment_ids tags transit_gateway_id" + }, + "AWS::EC2::TransitGatewayMeteringPolicyEntry": { + "a": "destination_cidr_block destination_port_range destination_transit_gateway_attachment_id destination_transit_gateway_attachment_type metered_account policy_rule_number protocol source_cidr_block source_port_range source_transit_gateway_attachment_id source_transit_gateway_attachment_type transit_gateway_metering_policy_id" + }, + "AWS::EC2::TransitGatewayMulticastDomain": { + "a": "options tags transit_gateway_id" + }, + "AWS::EC2::TransitGatewayMulticastDomainAssociation": { + "a": "subnet_id transit_gateway_attachment_id transit_gateway_multicast_domain_id" + }, + "AWS::EC2::TransitGatewayMulticastGroupMember": { + "a": "group_ip_address network_interface_id transit_gateway_multicast_domain_id" + }, + "AWS::EC2::TransitGatewayMulticastGroupSource": { + "a": "group_ip_address network_interface_id transit_gateway_multicast_domain_id" + }, + "AWS::EC2::TransitGatewayPeeringAttachment": { + "a": "peer_account_id peer_region peer_transit_gateway_id tags transit_gateway_id", + "x": [ + "AccepterAllowMultipathResilience", + "MultipathResilienceStatus", + "Options", + "RequesterAllowMultipathResilience", + "RequesterMultipathResilienceMode" + ] + }, + "AWS::EC2::TransitGatewayPolicyTable": { + "a": "tags transit_gateway_id" + }, + "AWS::EC2::TransitGatewayPolicyTableAssociation": { + "a": "transit_gateway_attachment_id transit_gateway_policy_table_id" + }, + "AWS::EC2::TransitGatewayPolicyTableEntry": { + "a": "policy_rule policy_rule_number target_route_table_id transit_gateway_policy_table_id" + }, + "AWS::EC2::TransitGatewayRoute": { + "a": "blackhole destination_cidr_block transit_gateway_attachment_id transit_gateway_route_table_id" + }, + "AWS::EC2::TransitGatewayRouteTable": { + "a": "tags transit_gateway_id" + }, + "AWS::EC2::TransitGatewayRouteTableAssociation": { + "a": "transit_gateway_attachment_id transit_gateway_route_table_id" + }, + "AWS::EC2::TransitGatewayRouteTablePropagation": { + "a": "transit_gateway_attachment_id transit_gateway_route_table_id" + }, + "AWS::EC2::TransitGatewayVpcAttachment": { + "a": "add_subnet_ids options remove_subnet_ids subnet_ids tags transit_gateway_id vpc_id" + }, + "AWS::EC2::VPC": { + "a": "cidr_block enable_dns_hostnames enable_dns_support instance_tenancy ipv_4_ipam_pool_id ipv_4_netmask_length tags vpc_encryption_control" + }, + "AWS::EC2::VPCBlockPublicAccessExclusion": { + "a": "internet_gateway_exclusion_mode subnet_id tags vpc_id" + }, + "AWS::EC2::VPCBlockPublicAccessOptions": { + "a": "internet_gateway_block_mode" + }, + "AWS::EC2::VPCCidrBlock": { + "a": "amazon_provided_ipv_6_cidr_block cidr_block ipv_4_ipam_pool_id ipv_4_netmask_length ipv_6_cidr_block ipv_6_cidr_block_network_border_group ipv_6_ipam_pool_id ipv_6_netmask_length ipv_6_pool vpc_id" + }, + "AWS::EC2::VPCDHCPOptionsAssociation": { + "a": "dhcp_options_id vpc_id" + }, + "AWS::EC2::VPCEncryptionControl": { + "a": "egress_only_internet_gateway_exclusion_input elastic_file_system_exclusion_input internet_gateway_exclusion_input lambda_exclusion_input mode nat_gateway_exclusion_input tags virtual_private_gateway_exclusion_input vpc_id vpc_lattice_exclusion_input vpc_peering_exclusion_input" + }, + "AWS::EC2::VPCEndpoint": { + "a": "dns_options ip_address_type policy_document private_dns_enabled resource_configuration_arn route_table_ids security_group_ids service_name service_network_arn service_region subnet_ids tags vpc_endpoint_type vpc_id", + "j": [ + "PolicyDocument" + ] + }, + "AWS::EC2::VPCEndpointConnectionNotification": { + "a": "connection_events connection_notification_arn service_id vpc_endpoint_id" + }, + "AWS::EC2::VPCEndpointService": { + "a": "acceptance_required contributor_insights_enabled gateway_load_balancer_arns network_load_balancer_arns payer_responsibility private_dns_name private_dns_name_configuration supported_ip_address_types supported_regions tags" + }, + "AWS::EC2::VPCEndpointServicePermissions": { + "a": "allowed_principals service_id", + "x": [ + "TransitGatewayAttachmentAllowedPrincipals" + ] + }, + "AWS::EC2::VPCGatewayAttachment": { + "a": "internet_gateway_id vpc_id vpn_gateway_id" + }, + "AWS::EC2::VPCPeeringConnection": { + "a": "assume_role_region peer_owner_id peer_region peer_role_arn peer_vpc_id tags vpc_id", + "x": [ + "MultipathResilienceStatus", + "PeerVpcPeeringConnectionOptions", + "VpcPeeringConnectionOptions" + ] + }, + "AWS::EC2::VPNConcentrator": { + "a": "tags transit_gateway_id type" + }, + "AWS::EC2::VPNConnection": { + "a": "customer_gateway_id enable_acceleration local_ipv_4_network_cidr local_ipv_6_network_cidr outside_ip_address_type pre_shared_key_storage remote_ipv_4_network_cidr remote_ipv_6_network_cidr static_routes_only tags transit_gateway_id transport_transit_gateway_attachment_id tunnel_bandwidth tunnel_inside_ip_version type vpn_concentrator_id vpn_gateway_id vpn_tunnel_options_specifications", + "x": [ + "VpnTunnelOptionsSpecifications.Phase1AdditionalKeyExchanges", + "VpnTunnelOptionsSpecifications.Phase2AdditionalKeyExchanges" + ] + }, + "AWS::EC2::VPNConnectionRoute": { + "a": "destination_cidr_block vpn_connection_id" + }, + "AWS::EC2::VPNGateway": { + "a": "amazon_side_asn tags type" + }, + "AWS::EC2::VerifiedAccessEndpoint": { + "a": "application_domain attachment_type cidr_options description domain_certificate_arn endpoint_domain_prefix endpoint_type load_balancer_options network_interface_options policy_document policy_enabled rds_options security_group_ids sse_specification tags verified_access_group_id" + }, + "AWS::EC2::VerifiedAccessGroup": { + "a": "description policy_document policy_enabled sse_specification tags verified_access_instance_id" + }, + "AWS::EC2::VerifiedAccessInstance": { + "a": "cidr_endpoints_custom_sub_domain description fips_enabled logging_configurations tags verified_access_trust_provider_ids verified_access_trust_providers" + }, + "AWS::EC2::VerifiedAccessTrustProvider": { + "a": "description device_options device_trust_provider_type native_application_oidc_options oidc_options policy_reference_name sse_specification tags trust_provider_type user_trust_provider_type" + }, + "AWS::EC2::Volume": { + "a": "auto_enable_io availability_zone availability_zone_id encrypted iops kms_key_id multi_attach_enabled outpost_arn size snapshot_id source_volume_id tags throughput volume_initialization_rate volume_type" + }, + "AWS::EC2::VolumeAttachment": { + "a": "device ebs_card_index instance_id volume_id" + }, + "AWS::ECR::PublicRepository": { + "a": "repository_catalog_data repository_name repository_policy_text tags", + "j": [ + "RepositoryPolicyText" + ] + }, + "AWS::ECR::PullThroughCacheRule": { + "a": "credential_arn custom_role_arn ecr_repository_prefix upstream_registry upstream_registry_url upstream_repository_prefix" + }, + "AWS::ECR::PullTimeUpdateExclusion": { + "a": "principal_arn" + }, + "AWS::ECR::RegistryPolicy": { + "a": "policy_text", + "j": [ + "PolicyText" + ] + }, + "AWS::ECR::RegistryScanningConfiguration": { + "a": "rules scan_type" + }, + "AWS::ECR::ReplicationConfiguration": { + "a": "replication_configuration", + "x": [ + "ReplicationConfiguration.Rules.DeleteReplication" + ] + }, + "AWS::ECR::Repository": { + "a": "empty_on_delete encryption_configuration image_scanning_configuration image_tag_mutability image_tag_mutability_exclusion_filters lifecycle_policy repository_name repository_policy_text tags", + "j": [ + "RepositoryPolicyText" + ] + }, + "AWS::ECR::RepositoryCreationTemplate": { + "a": "applied_for custom_role_arn description encryption_configuration image_tag_mutability image_tag_mutability_exclusion_filters lifecycle_policy prefix repository_policy resource_tags" + }, + "AWS::ECR::SigningConfiguration": { + "a": "rules" + }, + "AWS::ECS::CapacityProvider": { + "a": "auto_scaling_group_provider cluster_name managed_instances_provider name tags", + "r": { + "ManagedInstancesProvider.InstanceLaunchTemplate.Ec2InstanceProfileArn": "ec_2_instance_profile_arn" + } + }, + "AWS::ECS::Cluster": { + "a": "capacity_providers cluster_name cluster_settings configuration default_capacity_provider_strategy service_connect_defaults tags" + }, + "AWS::ECS::ClusterCapacityProviderAssociations": { + "a": "capacity_providers cluster default_capacity_provider_strategy", + "j": [ + "DefaultCapacityProviderStrategy.CapacityProvider" + ] + }, + "AWS::ECS::Daemon": { + "a": "capacity_provider_arns cluster_arn critical daemon_name daemon_task_definition_arn deployment_configuration enable_ecs_managed_tags enable_execute_command propagate_tags tags" + }, + "AWS::ECS::DaemonTaskDefinition": { + "a": "container_definitions cpu execution_role_arn family ipc_mode memory pid_mode tags task_role_arn volumes", + "m": [ + "ContainerDefinitions.FirelensConfiguration.Options", + "ContainerDefinitions.LogConfiguration.Options" + ] + }, + "AWS::ECS::ExpressGatewayService": { + "a": "cluster cpu execution_role_arn health_check_path infrastructure_role_arn memory network_configuration primary_container scaling_target service_name tags task_definition_arn task_role_arn" + }, + "AWS::ECS::Gateway": { + "a": "configuration deletion_protection gateway_name infrastructure_role_arn propagate_tags tags" + }, + "AWS::ECS::GatewayClusterAssociations": { + "a": "cluster gateway" + }, + "AWS::ECS::PrimaryTaskSet": { + "a": "cluster service task_set_id" + }, + "AWS::ECS::Service": { + "a": "availability_zone_rebalancing capacity_provider_strategy cluster deployment_configuration deployment_controller desired_count enable_ecs_managed_tags enable_execute_command force_new_deployment gateway_connectors health_check_grace_period_seconds launch_type load_balancers monitoring network_configuration placement_constraints placement_strategies platform_version propagate_tags role scheduling_strategy service_connect_configuration service_name service_registries tags task_definition volume_configurations vpc_lattice_configurations", + "j": [ + "DeploymentConfiguration.LifecycleHooks.HookDetails" + ], + "m": [ + "ServiceConnectConfiguration.LogConfiguration.Options" + ], + "x": [ + "GatewayConnectors.DeregistrationDelay" + ] + }, + "AWS::ECS::TaskDefinition": { + "a": "container_definitions cpu enable_fault_injection ephemeral_storage execution_role_arn family inference_accelerators ipc_mode memory network_mode pid_mode placement_constraints proxy_configuration requires_compatibilities runtime_platform tags task_role_arn volumes", + "m": [ + "ContainerDefinitions.DockerLabels", + "ContainerDefinitions.FirelensConfiguration.Options", + "ContainerDefinitions.LogConfiguration.Options", + "Volumes.DockerVolumeConfiguration.DriverOpts", + "Volumes.DockerVolumeConfiguration.Labels" + ], + "x": [ + "TrustedExecutionConfiguration" + ] + }, + "AWS::ECS::TaskSet": { + "a": "capacity_provider_strategy cluster external_id launch_type load_balancers network_configuration platform_version scale service service_registries tags task_definition" + }, + "AWS::EFS::AccessPoint": { + "a": "access_point_tags client_token file_system_id posix_user root_directory" + }, + "AWS::EFS::FileSystem": { + "a": "availability_zone_name backup_policy bypass_policy_lockout_safety_check encrypted file_system_policy file_system_protection file_system_tags kms_key_id lifecycle_policies performance_mode provisioned_throughput_in_mibps replication_configuration throughput_mode", + "j": [ + "FileSystemPolicy" + ] + }, + "AWS::EFS::MountTarget": { + "a": "file_system_id ip_address ip_address_type ipv_6_address security_groups subnet_id" + }, + "AWS::EKS::AccessEntry": { + "a": "access_policies cluster_name kubernetes_groups principal_arn tags type username" + }, + "AWS::EKS::Addon": { + "a": "addon_name addon_version cluster_name configuration_values namespace_config pod_identity_associations preserve_on_delete resolve_conflicts service_account_role_arn tags" + }, + "AWS::EKS::Capability": { + "a": "capability_name cluster_name configuration delete_propagation_policy role_arn tags type" + }, + "AWS::EKS::CertificateAuthority": { + "a": "cluster_name" + }, + "AWS::EKS::Cluster": { + "a": "access_config bootstrap_self_managed_addons compute_config control_plane_scaling_config deletion_protection encryption_config force kube_api_server_config kube_controller_manager_config kube_scheduler_config kubernetes_network_config logging name outpost_config remote_network_config resources_vpc_config role_arn rollback_config storage_config tags upgrade_policy version zonal_shift_config", + "x": [ + "ActiveCertificateAuthorityId", + "CertificateAuthority", + "KubeControllerManagerConfig.PodGcControllerConfig", + "KubernetesNetworkConfig.ElasticLoadBalancing.GatewayApi" + ] + }, + "AWS::EKS::FargateProfile": { + "a": "cluster_name fargate_profile_name pod_execution_role_arn selectors subnets tags" + }, + "AWS::EKS::IdentityProviderConfig": { + "a": "cluster_name identity_provider_config_name oidc tags type" + }, + "AWS::EKS::PodIdentityAssociation": { + "a": "cluster_name disable_session_tags namespace policy role_arn service_account tags target_role_arn", + "x": [ + "WorkloadIdentityConfig" + ] + }, + "AWS::EMR::SecurityConfiguration": { + "a": "name security_configuration", + "j": [ + "SecurityConfiguration" + ] + }, + "AWS::EMR::Step": { + "a": "action_on_failure encryption_key_arn hadoop_jar_step job_flow_id log_uri name" + }, + "AWS::EMR::Studio": { + "a": "auth_mode default_s3_location description encryption_key_arn engine_security_group_id idc_instance_arn idc_user_assignment idp_auth_url idp_relay_state_parameter_name name service_role subnet_ids tags trusted_identity_propagation_enabled user_role vpc_id workspace_security_group_id" + }, + "AWS::EMR::StudioSessionMapping": { + "a": "identity_name identity_type session_policy_arn studio_id" + }, + "AWS::EMR::WALWorkspace": { + "a": "tags wal_workspace_name" + }, + "AWS::EMRServerless::Application": { + "a": "architecture auto_start_configuration auto_stop_configuration image_configuration initial_capacity maximum_capacity name network_configuration release_label tags type worker_type_specifications", + "m": [ + "WorkerTypeSpecifications" + ], + "x": [ + "IdentityCenterConfiguration", + "InitialCapacity.Value.WorkerConfiguration.DiskType", + "InteractiveConfiguration", + "MonitoringConfiguration", + "RuntimeConfiguration", + "SchedulerConfiguration" + ] + }, + "AWS::EVS::Environment": { + "a": "connectivity_info environment_name hosts initial_vlans kms_key_id license_info service_access_security_groups service_access_subnet_id site_id tags terms_accepted vcf_hostnames vcf_version vpc_id" + }, + "AWS::ElastiCache::CacheCluster": { + "a": "auto_minor_version_upgrade az_mode cache_node_type cache_parameter_group_name cache_security_group_names cache_subnet_group_name cluster_name engine engine_version ip_discovery log_delivery_configurations network_type notification_topic_arn num_cache_nodes port preferred_availability_zone preferred_availability_zones preferred_maintenance_window snapshot_arns snapshot_name snapshot_retention_limit snapshot_window tags transit_encryption_enabled vpc_security_group_ids" + }, + "AWS::ElastiCache::GlobalReplicationGroup": { + "a": "automatic_failover_enabled cache_node_type cache_parameter_group_name engine engine_version global_node_group_count global_replication_group_description global_replication_group_id_suffix members regional_configurations tags" + }, + "AWS::ElastiCache::ParameterGroup": { + "a": "cache_parameter_group_family description properties tags", + "m": [ + "Properties" + ] + }, + "AWS::ElastiCache::ReplicationGroup": { + "a": "at_rest_encryption_enabled auth_token auto_minor_version_upgrade automatic_failover_enabled cache_node_type cache_parameter_group_name cache_security_group_names cache_subnet_group_name cluster_mode data_tiering_enabled durability engine engine_version global_replication_group_id ip_discovery kms_key_id log_delivery_configurations multi_az_enabled network_type node_group_configuration notification_topic_arn num_cache_clusters num_node_groups port preferred_cache_cluster_a_zs preferred_maintenance_window primary_cluster_id replicas_per_node_group replication_group_description replication_group_id security_group_ids snapshot_arns snapshot_name snapshot_retention_limit snapshot_window snapshotting_cluster_id tags transit_encryption_enabled transit_encryption_mode user_group_ids" + }, + "AWS::ElastiCache::ServerlessCache": { + "a": "cache_usage_limits connection_type daily_snapshot_time description endpoint engine final_snapshot_name kms_key_id major_engine_version network_type reader_endpoint security_group_ids serverless_cache_name snapshot_arns_to_restore snapshot_retention_limit subnet_ids tags user_group_id" + }, + "AWS::ElastiCache::ServerlessCacheSnapshot": { + "a": "kms_key_id serverless_cache_name serverless_cache_snapshot_name tags" + }, + "AWS::ElastiCache::Snapshot": { + "a": "cache_cluster_id kms_key_id replication_group_id snapshot_name tags" + }, + "AWS::ElastiCache::SubnetGroup": { + "a": "cache_subnet_group_name description subnet_ids tags" + }, + "AWS::ElastiCache::User": { + "a": "access_string authentication_mode engine no_password_required passwords tags user_id user_name" + }, + "AWS::ElastiCache::UserGroup": { + "a": "engine tags user_group_id user_ids" + }, + "AWS::ElasticBeanstalk::Application": { + "a": "application_name description resource_lifecycle_config" + }, + "AWS::ElasticBeanstalk::ApplicationVersion": { + "a": "application_name build_configuration description image_configuration process source_bundle" + }, + "AWS::ElasticBeanstalk::ConfigurationTemplate": { + "a": "application_name description environment_id option_settings platform_arn solution_stack_name source_configuration" + }, + "AWS::ElasticBeanstalk::Environment": { + "a": "application_name cname_prefix description environment_name operations_role option_settings platform_arn solution_stack_name tags template_name tier version_label" + }, + "AWS::ElasticLoadBalancing::LoadBalancer": { + "a": "access_logging_policy app_cookie_stickiness_policy availability_zones connection_draining_policy connection_settings cross_zone health_check instances lb_cookie_stickiness_policy listeners load_balancer_name policies scheme security_groups subnets tags" + }, + "AWS::ElasticLoadBalancingV2::Listener": { + "a": "alpn_policy certificates default_actions listener_attributes load_balancer_arn mutual_authentication port protocol ssl_policy tags", + "j": [ + "Certificates.CertificateArn", + "DefaultActions.AuthenticateCognitoConfig.UserPoolClientId" + ], + "m": [ + "DefaultActions.AuthenticateCognitoConfig.AuthenticationRequestExtraParams", + "DefaultActions.AuthenticateOidcConfig.AuthenticationRequestExtraParams" + ] + }, + "AWS::ElasticLoadBalancingV2::ListenerRule": { + "a": "actions conditions listener_arn priority tags transforms", + "m": [ + "Actions.AuthenticateCognitoConfig.AuthenticationRequestExtraParams", + "Actions.AuthenticateOidcConfig.AuthenticationRequestExtraParams" + ] + }, + "AWS::ElasticLoadBalancingV2::LoadBalancer": { + "a": "enable_capacity_reservation_provision_stabilize enable_prefix_for_ipv_6_source_nat enforce_security_group_inbound_rules_on_private_link_traffic ip_address_type ipv_4_ipam_pool_id load_balancer_attributes minimum_load_balancer_capacity name scheme security_groups subnet_mappings subnets tags type" + }, + "AWS::ElasticLoadBalancingV2::TargetGroup": { + "a": "health_check_enabled health_check_interval_seconds health_check_path health_check_port health_check_protocol health_check_timeout_seconds healthy_threshold_count ip_address_type matcher name port protocol protocol_version tags target_control_port target_group_attributes target_type targets unhealthy_threshold_count vpc_id" + }, + "AWS::ElasticLoadBalancingV2::TrustStore": { + "a": "ca_certificates_bundle_s3_bucket ca_certificates_bundle_s3_key ca_certificates_bundle_s3_object_version name tags" + }, + "AWS::ElasticLoadBalancingV2::TrustStoreRevocation": { + "a": "revocation_contents trust_store_arn" + }, + "AWS::ElementalInference::Dictionary": { + "a": "entries language name tags", + "m": [ + "Tags" + ] + }, + "AWS::ElementalInference::Feed": { + "a": "access_role_arn name outputs tags", + "m": [ + "Tags" + ] + }, + "AWS::EntityResolution::IdMappingWorkflow": { + "a": "description id_mapping_incremental_run_config id_mapping_techniques input_source_config output_source_config role_arn tags workflow_name", + "m": [ + "IdMappingTechniques.ProviderProperties.ProviderConfiguration" + ] + }, + "AWS::EntityResolution::IdNamespace": { + "a": "description id_mapping_workflow_properties id_namespace_name input_source_config role_arn tags type", + "m": [ + "IdMappingWorkflowProperties.ProviderProperties.ProviderConfiguration" + ] + }, + "AWS::EntityResolution::MatchingWorkflow": { + "a": "description incremental_run_config input_source_config output_source_config resolution_techniques role_arn tags workflow_name", + "m": [ + "ResolutionTechniques.ProviderProperties.ProviderConfiguration" + ] + }, + "AWS::EntityResolution::PolicyStatement": { + "a": "action arn condition effect principal statement_id" + }, + "AWS::EntityResolution::SchemaMapping": { + "a": "description mapped_input_fields schema_name tags" + }, + "AWS::EventSchemas::Discoverer": { + "a": "cross_account description source_arn tags" + }, + "AWS::EventSchemas::Registry": { + "a": "description registry_name tags" + }, + "AWS::EventSchemas::RegistryPolicy": { + "a": "policy registry_name revision_id", + "j": [ + "Policy" + ] + }, + "AWS::EventSchemas::Schema": { + "a": "content description registry_name schema_name tags type" + }, + "AWS::Events::ApiDestination": { + "a": "connection_arn description http_method invocation_endpoint invocation_rate_limit_per_second name" + }, + "AWS::Events::Archive": { + "a": "archive_name description event_pattern kms_key_identifier retention_days source_arn", + "j": [ + "EventPattern" + ] + }, + "AWS::Events::Connection": { + "a": "auth_parameters authorization_type description invocation_connectivity_parameters kms_key_identifier name" + }, + "AWS::Events::Endpoint": { + "a": "description event_buses name replication_config role_arn routing_config" + }, + "AWS::Events::EventBus": { + "a": "dead_letter_config description event_source_name kms_key_identifier log_config name policy tags", + "j": [ + "Policy" + ] + }, + "AWS::Events::EventBusPolicy": { + "a": "action condition event_bus_name principal statement statement_id", + "j": [ + "Statement" + ] + }, + "AWS::Events::Rule": { + "a": "description event_bus_name event_pattern name role_arn schedule_expression state tags targets", + "j": [ + "EventPattern" + ], + "m": [ + "Targets.HttpParameters.HeaderParameters", + "Targets.HttpParameters.QueryStringParameters", + "Targets.InputTransformer.InputPathsMap" + ] + }, + "AWS::EventsV2::EventBus": { + "a": "description encryption_configuration name storage_configuration tags" + }, + "AWS::EventsV2::EventSource": { + "a": "configuration description event_bus_arn name tags" + }, + "AWS::EventsV2::ResourcePolicy": { + "a": "event_bus_arn policy_document", + "j": [ + "PolicyDocument" + ] + }, + "AWS::EventsV2::Subscriber": { + "a": "batch_configuration description event_bus_arn filter_configuration invoke_configuration log_configuration name on_failure_configuration point_in_time_configuration resume_position retry_policy starting_position state tags transformer type", + "m": [ + "InvokeConfiguration.EventBusV2Parameters.Metadata", + "InvokeConfiguration.HttpParameters.HeaderParameters", + "InvokeConfiguration.HttpParameters.QueryStringParameters", + "InvokeConfiguration.SnsParameters.MessageAttributes", + "InvokeConfiguration.SqsParameters.MessageAttributes", + "InvokeConfiguration.SqsParameters.MessageSystemAttributes" + ] + }, + "AWS::Evidently::Experiment": { + "a": "description metric_goals name online_ab_config project randomization_salt remove_segment running_status sampling_rate segment tags treatments" + }, + "AWS::Evidently::Feature": { + "a": "default_variation description entity_overrides evaluation_strategy name project tags variations" + }, + "AWS::Evidently::Launch": { + "a": "description execution_status groups metric_monitors name project randomization_salt scheduled_splits_config tags" + }, + "AWS::Evidently::Project": { + "a": "app_config_resource data_delivery description name tags" + }, + "AWS::Evidently::Segment": { + "a": "description name pattern tags" + }, + "AWS::FIS::ExperimentTemplate": { + "a": "actions description experiment_options experiment_report_configuration log_configuration role_arn stop_conditions tags targets", + "m": [ + "Actions", + "Tags", + "Targets" + ] + }, + "AWS::FIS::TargetAccountConfiguration": { + "a": "account_id description experiment_template_id role_arn" + }, + "AWS::FMS::ApplicationsList": { + "a": "apps_list list_name tags" + }, + "AWS::FMS::NotificationChannel": { + "a": "sns_role_name sns_topic_arn" + }, + "AWS::FMS::Policy": { + "a": "delete_all_policy_resources exclude_map exclude_resource_tags include_map policy_description policy_name remediation_enabled resource_set_ids resource_tag_logical_operator resource_tags resource_type resource_type_list resources_clean_up security_service_policy_data tags" + }, + "AWS::FMS::ProtocolsList": { + "a": "list_name protocols_list tags" + }, + "AWS::FMS::ResourceSet": { + "a": "description name resource_type_list resources tags" + }, + "AWS::FSx::DataRepositoryAssociation": { + "a": "batch_import_meta_data_on_create data_repository_path file_system_id file_system_path imported_file_chunk_size s3 tags" + }, + "AWS::FSx::S3AccessPointAttachment": { + "a": "name ontap_configuration open_zfs_configuration s3_access_point type", + "j": [ + "S3AccessPoint.Policy" + ], + "x": [ + "Lifecycle" + ] + }, + "AWS::FSx::Snapshot": { + "a": "name tags volume_id" + }, + "AWS::FSx::StorageVirtualMachine": { + "a": "active_directory_configuration file_system_id name root_volume_security_style svm_admin_password tags" + }, + "AWS::FSx::Volume": { + "a": "backup_id name ontap_configuration open_zfs_configuration tags volume_type" + }, + "AWS::FinSpace::Environment": { + "a": "data_bundles description federation_mode federation_parameters kms_key_id name superuser_parameters tags" + }, + "AWS::Forecast::Dataset": { + "a": "data_frequency dataset_name dataset_type domain encryption_config schema tags" + }, + "AWS::Forecast::DatasetGroup": { + "a": "dataset_arns dataset_group_name domain tags" + }, + "AWS::FraudDetector::Detector": { + "a": "associated_models description detector_id detector_version_status event_type rule_execution_mode rules tags" + }, + "AWS::FraudDetector::EntityType": { + "a": "description name tags" + }, + "AWS::FraudDetector::EventType": { + "a": "description entity_types event_variables labels name tags" + }, + "AWS::FraudDetector::Label": { + "a": "description name tags" + }, + "AWS::FraudDetector::List": { + "a": "description elements name tags variable_type" + }, + "AWS::FraudDetector::Outcome": { + "a": "description name tags" + }, + "AWS::FraudDetector::Variable": { + "a": "data_source data_type default_value description name tags variable_type" + }, + "AWS::GameLift::Alias": { + "a": "description name routing_strategy tags" + }, + "AWS::GameLift::Build": { + "a": "name operating_system server_sdk_version storage_location tags version" + }, + "AWS::GameLift::ContainerFleet": { + "a": "billing_type deployment_configuration description fleet_role_arn game_server_container_group_definition_name game_server_container_groups_per_instance game_session_creation_limit_policy instance_connection_port_range instance_inbound_permissions instance_type locations log_configuration metric_groups new_game_session_protection_policy per_instance_container_group_definition_name player_gateway_mode scaling_policies tags" + }, + "AWS::GameLift::ContainerGroupDefinition": { + "a": "container_group_type game_server_container_definition name operating_system source_version_number support_container_definitions tags total_memory_limit_mebibytes total_vcpu_limit version_description" + }, + "AWS::GameLift::Fleet": { + "a": "anywhere_configuration apply_capacity build_id certificate_configuration compute_type description desired_ec2_instances ec2_inbound_permissions ec2_instance_type fleet_type instance_role_arn instance_role_credentials_provider locations log_paths max_size metric_groups min_size name new_game_session_protection_policy peer_vpc_aws_account_id peer_vpc_id player_gateway_configuration player_gateway_mode resource_creation_limit_policy runtime_configuration scaling_policies script_id server_launch_parameters server_launch_path tags" + }, + "AWS::GameLift::GameServerGroup": { + "a": "auto_scaling_policy balancing_strategy delete_option game_server_group_name game_server_protection_policy instance_definitions launch_template max_size min_size role_arn tags vpc_subnets" + }, + "AWS::GameLift::GameSessionQueue": { + "a": "custom_event_data destinations filter_configuration log_configuration name notification_target player_latency_policies priority_configuration tags timeout_in_seconds" + }, + "AWS::GameLift::Location": { + "a": "location_name tags" + }, + "AWS::GameLift::MatchmakingConfiguration": { + "a": "acceptance_required acceptance_timeout_seconds additional_player_count backfill_mode creation_time custom_event_data description flex_match_mode game_properties game_session_data game_session_queue_arns name notification_target request_timeout_seconds rule_set_arn rule_set_name tags" + }, + "AWS::GameLift::MatchmakingRuleSet": { + "a": "name rule_set_body tags" + }, + "AWS::GameLift::Script": { + "a": "name node_js_version storage_location tags version" + }, + "AWS::GlobalAccelerator::Accelerator": { + "a": "enabled flow_logs_enabled flow_logs_s3_bucket flow_logs_s3_prefix ip_address_type ip_addresses name tags" + }, + "AWS::GlobalAccelerator::CrossAccountAttachment": { + "a": "name principals resources tags" + }, + "AWS::GlobalAccelerator::EndpointGroup": { + "a": "endpoint_configurations endpoint_group_region health_check_interval_seconds health_check_path health_check_port health_check_protocol listener_arn port_overrides threshold_count traffic_dial_percentage" + }, + "AWS::GlobalAccelerator::Listener": { + "a": "accelerator_arn client_affinity port_ranges protocol" + }, + "AWS::Glue::Blueprint": { + "a": "blueprint_location description name tags" + }, + "AWS::Glue::Catalog": { + "a": "allow_full_table_external_data_access catalog_properties create_database_default_permissions create_table_default_permissions description federated_catalog name overwrite_child_resource_permissions_with_default parameters tags target_redshift_catalog", + "m": [ + "CatalogProperties.CustomProperties", + "Parameters" + ], + "x": [ + "FederatedCatalog.ConnectionType", + "FederatedCatalog.SyncConfiguration" + ] + }, + "AWS::Glue::Classifier": { + "a": "csv_classifier grok_classifier json_classifier xml_classifier" + }, + "AWS::Glue::Connection": { + "a": "catalog_id connection_input tags", + "j": [ + "ConnectionInput.AthenaProperties", + "ConnectionInput.AuthenticationConfiguration.CustomAuthenticationCredentials", + "ConnectionInput.AuthenticationConfiguration.OAuth2Properties.TokenUrlParametersMap", + "ConnectionInput.ConnectionProperties", + "ConnectionInput.PythonProperties", + "ConnectionInput.SparkProperties", + "Tags" + ] + }, + "AWS::Glue::ConnectionType": { + "a": "connection_properties connection_type connector_authentication_configuration description integration_type rest_configuration tags", + "m": [ + "RestConfiguration.EntityConfigurations", + "RestConfiguration.GlobalSourceConfiguration.FilterConfiguration.OperatorMappings" + ] + }, + "AWS::Glue::Crawler": { + "a": "classifiers configuration crawler_security_configuration database_name description lake_formation_configuration name recrawl_policy role schedule schema_change_policy table_prefix tags targets", + "j": [ + "Tags" + ] + }, + "AWS::Glue::CustomEntityType": { + "a": "context_words name regex_string tags", + "j": [ + "Tags" + ] + }, + "AWS::Glue::DataCatalogEncryptionSettings": { + "a": "catalog_id data_catalog_encryption_settings" + }, + "AWS::Glue::DataQualityRuleset": { + "a": "client_token description name ruleset tags target_table", + "m": [ + "Tags" + ] + }, + "AWS::Glue::Database": { + "a": "catalog_id database_input database_name", + "j": [ + "DatabaseInput.Parameters" + ] + }, + "AWS::Glue::IdentityCenterConfiguration": { + "a": "instance_arn scopes user_background_sessions_enabled" + }, + "AWS::Glue::Integration": { + "a": "additional_encryption_context data_filter description integration_config integration_name kms_key_id source_arn tags target_arn", + "m": [ + "AdditionalEncryptionContext", + "IntegrationConfig.SourceProperties" + ] + }, + "AWS::Glue::IntegrationResourceProperty": { + "a": "resource_arn source_processing_properties tags target_processing_properties" + }, + "AWS::Glue::Job": { + "a": "allocated_capacity command connections default_arguments description execution_class execution_property glue_version job_mode job_run_queuing_enabled log_uri maintenance_window max_capacity max_retries name non_overridable_arguments notification_property number_of_workers role security_configuration tags timeout worker_type", + "j": [ + "DefaultArguments", + "NonOverridableArguments", + "Tags" + ] + }, + "AWS::Glue::MLTransform": { + "a": "description glue_version input_record_tables max_capacity max_retries name number_of_workers role tags timeout transform_encryption transform_parameters worker_type", + "m": [ + "Tags" + ] + }, + "AWS::Glue::Partition": { + "a": "catalog_id database_name partition_input table_name", + "j": [ + "PartitionInput.Parameters", + "PartitionInput.StorageDescriptor.Parameters", + "PartitionInput.StorageDescriptor.SerdeInfo.Parameters", + "PartitionInput.StorageDescriptor.SkewedInfo.SkewedColumnValueLocationMaps" + ] + }, + "AWS::Glue::Registry": { + "a": "description name tags" + }, + "AWS::Glue::Schema": { + "a": "checkpoint_version compatibility data_format description name registry schema_definition tags" + }, + "AWS::Glue::SchemaVersion": { + "a": "schema schema_definition" + }, + "AWS::Glue::SchemaVersionMetadata": { + "a": "key schema_version_id value" + }, + "AWS::Glue::SecurityConfiguration": { + "a": "encryption_configuration name" + }, + "AWS::Glue::Session": { + "a": "command connections default_arguments description glue_version idle_timeout max_capacity number_of_workers request_origin role security_configuration session_id tags timeout worker_type", + "m": [ + "DefaultArguments" + ] + }, + "AWS::Glue::Table": { + "a": "catalog_id database_name name open_table_format_input table_input", + "j": [ + "TableInput.Parameters", + "TableInput.StorageDescriptor.Parameters", + "TableInput.StorageDescriptor.SerdeInfo.Parameters", + "TableInput.StorageDescriptor.SkewedInfo.SkewedColumnValueLocationMaps" + ], + "m": [ + "OpenTableFormatInput.IcebergInput.IcebergTableInput.Properties" + ] + }, + "AWS::Glue::TableOptimizer": { + "a": "catalog_id database_name table_name table_optimizer_configuration type" + }, + "AWS::Glue::Trigger": { + "a": "actions description event_batching_condition name predicate schedule start_on_creation tags type workflow_name", + "j": [ + "Actions.Arguments", + "Tags" + ] + }, + "AWS::Glue::UserDefinedFunction": { + "a": "class_name database_name function_name function_type owner_name owner_type resource_uris" + }, + "AWS::Glue::Workflow": { + "a": "default_run_properties description max_concurrent_runs name tags", + "j": [ + "DefaultRunProperties", + "Tags" + ] + }, + "AWS::Grafana::Workspace": { + "a": "account_access_type authentication_providers client_token data_sources description grafana_version name network_access_control notification_destinations organization_role_name organizational_units permission_type plugin_admin_enabled role_arn saml_configuration stack_set_name tags vpc_configuration" + }, + "AWS::GreengrassV2::ComponentVersion": { + "a": "inline_recipe lambda_function tags", + "m": [ + "LambdaFunction.ComponentDependencies", + "LambdaFunction.ComponentLambdaParameters.EnvironmentVariables", + "LambdaFunction.ComponentPlatforms.Attributes", + "Tags" + ] + }, + "AWS::GreengrassV2::Deployment": { + "a": "components deployment_name deployment_policies iot_job_configuration parent_target_arn tags target_arn", + "m": [ + "Components", + "Tags" + ] + }, + "AWS::GroundStation::Config": { + "a": "config_data name tags" + }, + "AWS::GroundStation::DataflowEndpointGroup": { + "a": "contact_post_pass_duration_seconds contact_pre_pass_duration_seconds endpoint_details tags" + }, + "AWS::GroundStation::DataflowEndpointGroupV2": { + "a": "contact_post_pass_duration_seconds contact_pre_pass_duration_seconds endpoints tags" + }, + "AWS::GroundStation::MissionProfile": { + "a": "contact_post_pass_duration_seconds contact_pre_pass_duration_seconds dataflow_edges minimum_viable_contact_duration_seconds name streams_kms_key streams_kms_role tags telemetry_sink_config_arn tracking_config_arn" + }, + "AWS::GuardDuty::CustomDetectionRuleAssociation": { + "a": "mode rule_id tags" + }, + "AWS::GuardDuty::Detector": { + "a": "data_sources enable features finding_publishing_frequency tags", + "r": { + "DataSources.MalwareProtection.ScanEc2InstanceWithFindings": "scan_ec_2_instance_with_findings" + } + }, + "AWS::GuardDuty::Filter": { + "a": "action description detector_id finding_criteria name rank tags", + "m": [ + "FindingCriteria.Criterion" + ] + }, + "AWS::GuardDuty::IPSet": { + "a": "activate detector_id expected_bucket_owner format location name tags" + }, + "AWS::GuardDuty::MalwareProtectionPlan": { + "a": "actions protected_resource role tags" + }, + "AWS::GuardDuty::Master": { + "a": "detector_id invitation_id master_id" + }, + "AWS::GuardDuty::Member": { + "a": "detector_id disable_email_notification email member_id message status" + }, + "AWS::GuardDuty::PublishingDestination": { + "a": "destination_properties destination_type detector_id tags" + }, + "AWS::GuardDuty::ThreatEntitySet": { + "a": "activate detector_id expected_bucket_owner format location name tags" + }, + "AWS::GuardDuty::ThreatIntelSet": { + "a": "activate detector_id expected_bucket_owner format location name tags" + }, + "AWS::GuardDuty::TrustedEntitySet": { + "a": "activate detector_id expected_bucket_owner format location name tags" + }, + "AWS::HealthAgent::Domain": { + "a": "name tags" + }, + "AWS::HealthImaging::Datastore": { + "a": "datastore_name kms_key_arn tags", + "m": [ + "Tags" + ] + }, + "AWS::HealthLake::DataTransformationProfile": { + "a": "kms_key_id profile_description profile_name source source_format tags", + "m": [ + "Source.ProfileMapping.ProfileMapping" + ] + }, + "AWS::HealthLake::FHIRDatastore": { + "a": "analytics_configuration datastore_name datastore_type_version identity_provider_configuration nlp_configuration preload_data_config profile_configuration sse_configuration tags" + }, + "AWS::IAM::Group": { + "a": "group_name managed_policy_arns path policies", + "j": [ + "Policies.PolicyDocument" + ] + }, + "AWS::IAM::GroupPolicy": { + "a": "group_name policy_document policy_name", + "j": [ + "PolicyDocument" + ] + }, + "AWS::IAM::InstanceProfile": { + "a": "instance_profile_name path roles" + }, + "AWS::IAM::ManagedPolicy": { + "a": "description groups managed_policy_name path policy_document roles users", + "j": [ + "PolicyDocument" + ] + }, + "AWS::IAM::OIDCProvider": { + "a": "client_id_list tags thumbprint_list url" + }, + "AWS::IAM::Role": { + "a": "assume_role_policy_document description managed_policy_arns max_session_duration path permissions_boundary policies role_name tags", + "j": [ + "AssumeRolePolicyDocument", + "Policies.PolicyDocument" + ] + }, + "AWS::IAM::RolePolicy": { + "a": "policy_document policy_name role_name", + "j": [ + "PolicyDocument" + ] + }, + "AWS::IAM::SAMLProvider": { + "a": "add_private_key assertion_encryption_mode name private_key_list remove_private_key saml_metadata_document tags" + }, + "AWS::IAM::ServerCertificate": { + "a": "certificate_body certificate_chain path private_key server_certificate_name tags" + }, + "AWS::IAM::ServiceLinkedRole": { + "a": "aws_service_name custom_suffix description" + }, + "AWS::IAM::User": { + "a": "groups login_profile managed_policy_arns path permissions_boundary policies tags user_name", + "j": [ + "Policies.PolicyDocument" + ] + }, + "AWS::IAM::UserPolicy": { + "a": "policy_document policy_name user_name", + "j": [ + "PolicyDocument" + ] + }, + "AWS::IAM::VirtualMFADevice": { + "a": "path tags users virtual_mfa_device_name" + }, + "AWS::IVS::AdConfiguration": { + "a": "media_tailor_playback_configurations name post_roll_configuration tags" + }, + "AWS::IVS::Channel": { + "a": "authorized container_format insecure_ingest latency_mode multitrack_input_configuration name preset recording_configuration_arn tags type" + }, + "AWS::IVS::EncoderConfiguration": { + "a": "name tags video" + }, + "AWS::IVS::IngestConfiguration": { + "a": "ingest_protocol insecure_ingest name stage_arn tags user_id" + }, + "AWS::IVS::PlaybackKeyPair": { + "a": "name public_key_material tags" + }, + "AWS::IVS::PlaybackRestrictionPolicy": { + "a": "allowed_countries allowed_origins enable_strict_origin_enforcement name tags" + }, + "AWS::IVS::PublicKey": { + "a": "name public_key_material tags" + }, + "AWS::IVS::RecordingConfiguration": { + "a": "destination_configuration name recording_reconnect_window_seconds rendition_configuration tags thumbnail_configuration" + }, + "AWS::IVS::Stage": { + "a": "auto_participant_recording_configuration name tags" + }, + "AWS::IVS::StorageConfiguration": { + "a": "name s3 tags" + }, + "AWS::IVS::StreamKey": { + "a": "channel_arn tags" + }, + "AWS::IVSChat::LoggingConfiguration": { + "a": "destination_configuration name tags" + }, + "AWS::IVSChat::Room": { + "a": "logging_configuration_identifiers maximum_message_length maximum_message_rate_per_second message_review_handler name tags" + }, + "AWS::IdentityStore::Group": { + "a": "description display_name identity_store_id" + }, + "AWS::IdentityStore::GroupMembership": { + "a": "group_id identity_store_id member_id" + }, + "AWS::IdentityStore::User": { + "a": "addresses birthdate display_name emails identity_store_id locale name nick_name phone_numbers photos preferred_language profile_url roles timezone title user_name user_type website" + }, + "AWS::ImageBuilder::Component": { + "a": "change_description data description kms_key_id name platform supported_os_versions tags uri version", + "m": [ + "Tags" + ] + }, + "AWS::ImageBuilder::ContainerRecipe": { + "a": "components container_type description dockerfile_template_data dockerfile_template_uri image_os_version_override instance_configuration kms_key_id name parent_image platform_override tags target_repository version working_directory", + "m": [ + "Tags" + ] + }, + "AWS::ImageBuilder::DistributionConfiguration": { + "a": "description distributions name tags", + "m": [ + "Distributions.AmiDistributionConfiguration.AmiTags", + "Tags" + ] + }, + "AWS::ImageBuilder::Image": { + "a": "container_recipe_arn deletion_settings distribution_configuration_arn enhanced_image_metadata_enabled execution_role image_pipeline_execution_settings image_recipe_arn image_scanning_configuration image_tests_configuration infrastructure_configuration_arn logging_configuration tags workflows", + "m": [ + "Tags" + ] + }, + "AWS::ImageBuilder::ImagePipeline": { + "a": "container_recipe_arn description distribution_configuration_arn enhanced_image_metadata_enabled execution_role image_recipe_arn image_scanning_configuration image_tags image_tests_configuration infrastructure_configuration_arn logging_configuration name schedule status tags workflows", + "m": [ + "ImageTags", + "Tags" + ] + }, + "AWS::ImageBuilder::ImageRecipe": { + "a": "additional_instance_configuration ami_tags ami_watermarks block_device_mappings components description name parent_image tags version working_directory", + "m": [ + "AmiTags", + "Tags" + ] + }, + "AWS::ImageBuilder::InfrastructureConfiguration": { + "a": "description instance_metadata_options instance_profile_name instance_types key_pair logging name parent_instance placement resource_tags security_group_ids sns_topic_arn subnet_id tags terminate_instance_on_completion terminate_instance_on_failure", + "m": [ + "ResourceTags", + "Tags" + ] + }, + "AWS::ImageBuilder::LifecyclePolicy": { + "a": "description execution_role name policy_details resource_selection resource_type status tags", + "m": [ + "PolicyDetails.ExclusionRules.Amis.TagMap", + "PolicyDetails.ExclusionRules.TagMap", + "ResourceSelection.TagMap", + "Tags" + ] + }, + "AWS::ImageBuilder::Workflow": { + "a": "change_description data description kms_key_id name tags type uri version", + "m": [ + "Tags" + ] + }, + "AWS::Inspector::AssessmentTarget": { + "a": "assessment_target_name resource_group_arn" + }, + "AWS::Inspector::AssessmentTemplate": { + "a": "assessment_target_arn assessment_template_name duration_in_seconds rules_package_arns user_attributes_for_findings" + }, + "AWS::Inspector::ResourceGroup": { + "a": "resource_group_tags" + }, + "AWS::InspectorV2::CisScanConfiguration": { + "a": "scan_name schedule security_level tags targets", + "j": [ + "Schedule.OneTime" + ], + "m": [ + "Tags", + "Targets.TargetResourceTags" + ] + }, + "AWS::InspectorV2::CodeSecurityIntegration": { + "a": "create_integration_details name tags type update_integration_details", + "m": [ + "Tags" + ] + }, + "AWS::InspectorV2::CodeSecurityScanConfiguration": { + "a": "configuration level name scope_settings tags", + "m": [ + "Tags" + ] + }, + "AWS::InspectorV2::Connector": { + "a": "description name provider_configuration provider_name tags", + "x": [ + "Provider", + "ProviderConfiguration.Gcp" + ] + }, + "AWS::InspectorV2::Filter": { + "a": "description filter_action filter_criteria name tags", + "m": [ + "Tags" + ], + "r": { + "FilterCriteria.Ec2InstanceImageId": "ec_2_instance_image_id", + "FilterCriteria.Ec2InstanceSubnetId": "ec_2_instance_subnet_id", + "FilterCriteria.Ec2InstanceVpcId": "ec_2_instance_vpc_id" + } + }, + "AWS::Interconnect::Connection": { + "a": "activation_key attach_point bandwidth description environment_id remote_account remote_owner_account tags", + "x": [ + "Provider" + ] + }, + "AWS::InternetMonitor::Monitor": { + "a": "health_events_config include_linked_accounts internet_measurements_log_delivery linked_account_id max_city_networks_to_monitor monitor_name resources resources_to_add resources_to_remove status tags traffic_percentage_to_monitor" + }, + "AWS::Invoicing::InvoiceUnit": { + "a": "description invoice_receiver name resource_tags rule tax_inheritance_disabled" + }, + "AWS::Invoicing::ProcurementPortalPreference": { + "a": "buyer_domain buyer_identifier contacts einvoice_delivery_enabled einvoice_delivery_preference procurement_portal_instance_endpoint procurement_portal_name procurement_portal_shared_secret purchase_order_retrieval_enabled selector supplier_domain supplier_identifier tags test_env_preference" + }, + "AWS::IoT::AccountAuditConfiguration": { + "a": "account_id audit_check_configurations audit_notification_target_configurations role_arn" + }, + "AWS::IoT::Authorizer": { + "a": "authorizer_function_arn authorizer_name enable_caching_for_http signing_disabled status tags token_key_name token_signing_public_keys", + "m": [ + "TokenSigningPublicKeys" + ] + }, + "AWS::IoT::BillingGroup": { + "a": "billing_group_name billing_group_properties tags" + }, + "AWS::IoT::CACertificate": { + "a": "auto_registration_status ca_certificate_pem certificate_mode registration_config remove_auto_registration status tags verification_certificate_pem" + }, + "AWS::IoT::Certificate": { + "a": "ca_certificate_pem certificate_mode certificate_pem certificate_signing_request status" + }, + "AWS::IoT::CertificateProvider": { + "a": "account_default_for_operations certificate_provider_name lambda_function_arn tags" + }, + "AWS::IoT::Command": { + "a": "command_id created_at deprecated description display_name last_updated_at mandatory_parameters namespace payload payload_template pending_deletion preprocessor role_arn tags" + }, + "AWS::IoT::CustomMetric": { + "a": "display_name metric_name metric_type tags" + }, + "AWS::IoT::Dimension": { + "a": "name string_values tags type" + }, + "AWS::IoT::DomainConfiguration": { + "a": "application_protocol authentication_type authorizer_config client_certificate_config domain_configuration_name domain_configuration_status domain_name server_certificate_arns server_certificate_config service_type tags tls_config validation_certificate_arn" + }, + "AWS::IoT::EncryptionConfiguration": { + "a": "encryption_type kms_access_role_arn kms_key_arn" + }, + "AWS::IoT::FleetMetric": { + "a": "aggregation_field aggregation_type description index_name metric_name period query_string query_version tags unit" + }, + "AWS::IoT::Job": { + "a": "abort_config description destination_package_versions document document_parameters document_source job_executions_retry_config job_executions_rollout_config job_id job_template_arn presigned_url_config scheduling_config tags target_selection targets timeout_config", + "m": [ + "DocumentParameters" + ] + }, + "AWS::IoT::JobTemplate": { + "a": "abort_config description destination_package_versions document document_source job_arn job_executions_retry_config job_executions_rollout_config job_template_id maintenance_windows presigned_url_config tags timeout_config" + }, + "AWS::IoT::Logging": { + "a": "account_id default_log_level event_configurations role_arn" + }, + "AWS::IoT::MitigationAction": { + "a": "action_name action_params role_arn tags" + }, + "AWS::IoT::OTAUpdate": { + "a": "additional_parameters aws_job_abort_config aws_job_executions_rollout_config aws_job_presigned_url_config aws_job_timeout_config description files ota_update_id protocols role_arn tags target_selection targets", + "m": [ + "AdditionalParameters", + "Files.Attributes" + ] + }, + "AWS::IoT::Policy": { + "a": "policy_document policy_name tags", + "j": [ + "PolicyDocument" + ] + }, + "AWS::IoT::PolicyPrincipalAttachment": { + "a": "policy_name principal" + }, + "AWS::IoT::ProvisioningTemplate": { + "a": "description enabled pre_provisioning_hook provisioning_role_arn tags template_body template_name template_type" + }, + "AWS::IoT::ResourceSpecificLogging": { + "a": "log_level target_name target_type" + }, + "AWS::IoT::RoleAlias": { + "a": "credential_duration_seconds role_alias role_arn tags" + }, + "AWS::IoT::ScheduledAudit": { + "a": "day_of_month day_of_week frequency scheduled_audit_name tags target_check_names" + }, + "AWS::IoT::SecurityProfile": { + "a": "additional_metrics_to_retain_v2 alert_targets behaviors metrics_export_config security_profile_description security_profile_name tags target_arns", + "m": [ + "AlertTargets" + ] + }, + "AWS::IoT::SoftwarePackage": { + "a": "description package_name tags" + }, + "AWS::IoT::SoftwarePackageVersion": { + "a": "artifact attributes description package_name recipe sbom tags version_name", + "m": [ + "Attributes" + ] + }, + "AWS::IoT::Stream": { + "a": "description files role_arn stream_id tags" + }, + "AWS::IoT::Thing": { + "a": "attribute_payload thing_name", + "m": [ + "AttributePayload.Attributes" + ] + }, + "AWS::IoT::ThingGroup": { + "a": "parent_group_name query_string tags thing_group_name thing_group_properties", + "m": [ + "ThingGroupProperties.AttributePayload.Attributes" + ] + }, + "AWS::IoT::ThingPrincipalAttachment": { + "a": "principal thing_name thing_principal_type" + }, + "AWS::IoT::ThingType": { + "a": "deprecate_thing_type tags thing_type_name thing_type_properties" + }, + "AWS::IoT::TopicRule": { + "a": "rule_name tags topic_rule_payload", + "m": [ + "TopicRulePayload.Actions.InfluxDB.Tags", + "TopicRulePayload.Actions.Kafka.ClientProperties", + "TopicRulePayload.ErrorAction.InfluxDB.Tags", + "TopicRulePayload.ErrorAction.Kafka.ClientProperties" + ] + }, + "AWS::IoT::TopicRuleDestination": { + "a": "http_url_properties influx_db_properties status vpc_properties" + }, + "AWS::IoTAnalytics::Channel": { + "a": "channel_name channel_storage retention_period tags", + "j": [ + "ChannelStorage.ServiceManagedS3" + ] + }, + "AWS::IoTAnalytics::Dataset": { + "a": "actions content_delivery_rules dataset_name late_data_rules retention_period tags triggers versioning_configuration" + }, + "AWS::IoTAnalytics::Datastore": { + "a": "datastore_name datastore_partitions datastore_storage file_format_configuration retention_period tags", + "j": [ + "DatastoreStorage.ServiceManagedS3", + "FileFormatConfiguration.JsonConfiguration" + ] + }, + "AWS::IoTAnalytics::Pipeline": { + "a": "pipeline_activities pipeline_name tags", + "m": [ + "PipelineActivities.AddAttributes.Attributes" + ] + }, + "AWS::IoTCoreDeviceAdvisor::SuiteDefinition": { + "a": "suite_definition_configuration tags" + }, + "AWS::IoTFleetWise::Campaign": { + "a": "action collection_scheme compression data_destination_configs data_extra_dimensions data_partitions description diagnostics_mode expiry_time name post_trigger_collection_duration priority signal_catalog_arn signals_to_collect signals_to_fetch spooling_mode start_time tags target_arn" + }, + "AWS::IoTFleetWise::Fleet": { + "a": "description fleet_id signal_catalog_arn tags" + }, + "AWS::IoTFleetWise::ModelManifest": { + "a": "description name nodes signal_catalog_arn status tags" + }, + "AWS::IoTFleetWise::SignalCatalog": { + "a": "description name node_counts nodes tags" + }, + "AWS::IoTFleetWise::StateTemplate": { + "a": "data_extra_dimensions description metadata_extra_dimensions name signal_catalog_arn state_template_properties tags" + }, + "AWS::IoTFleetWise::Vehicle": { + "a": "association_behavior attributes decoder_manifest_arn model_manifest_arn name state_templates tags", + "m": [ + "Attributes" + ] + }, + "AWS::IoTSecureTunneling::Tunnel": { + "a": "description destination_config tags timeout_config" + }, + "AWS::IoTSiteWise::AccessPolicy": { + "a": "access_policy_identity access_policy_permission access_policy_resource" + }, + "AWS::IoTSiteWise::Application": { + "a": "description idc_instance_arn name tags workspace_name" + }, + "AWS::IoTSiteWise::Asset": { + "a": "asset_description asset_external_id asset_hierarchies asset_model_id asset_name asset_properties tags" + }, + "AWS::IoTSiteWise::AssetModel": { + "a": "asset_model_composite_models asset_model_description asset_model_external_id asset_model_hierarchies asset_model_name asset_model_properties asset_model_type enforced_asset_model_interface_relationships tags" + }, + "AWS::IoTSiteWise::Dashboard": { + "a": "dashboard_definition dashboard_description dashboard_name project_id tags" + }, + "AWS::IoTSiteWise::Dataset": { + "a": "dataset_config dataset_description dataset_name dataset_source dataset_type tags workspace_name" + }, + "AWS::IoTSiteWise::Gateway": { + "a": "gateway_capability_summaries gateway_name gateway_platform gateway_version tags" + }, + "AWS::IoTSiteWise::Pipeline": { + "a": "computations description environment_variables pipeline_name tags workspace_name", + "m": [ + "Computations.EnvironmentVariables", + "EnvironmentVariables" + ] + }, + "AWS::IoTSiteWise::Portal": { + "a": "alarms notification_sender_email portal_auth_mode portal_contact_email portal_description portal_name portal_type portal_type_configuration role_arn tags", + "m": [ + "PortalTypeConfiguration" + ] + }, + "AWS::IoTSiteWise::Project": { + "a": "asset_ids portal_id project_description project_name tags" + }, + "AWS::IoTSiteWise::Task": { + "a": "description tags task_configuration task_name workspace_name", + "m": [ + "TaskConfiguration.ContainerTaskConfiguration.EnvironmentVariables" + ] + }, + "AWS::IoTSiteWise::Workspace": { + "a": "encryption_configuration kms_key_id tags workspace_description workspace_name" + }, + "AWS::IoTTwinMaker::Scene": { + "a": "capabilities content_location description scene_id scene_metadata tags workspace_id", + "m": [ + "GeneratedSceneMetadata", + "SceneMetadata", + "Tags" + ] + }, + "AWS::IoTTwinMaker::SyncJob": { + "a": "sync_role sync_source tags workspace_id", + "m": [ + "Tags" + ] + }, + "AWS::IoTTwinMaker::Workspace": { + "a": "description role s3_location tags workspace_id", + "m": [ + "Tags" + ] + }, + "AWS::IoTWireless::Destination": { + "a": "description expression expression_type name role_arn tags" + }, + "AWS::IoTWireless::DeviceProfile": { + "a": "lo_ra_wan name tags" + }, + "AWS::IoTWireless::FuotaTask": { + "a": "associate_multicast_group associate_wireless_device description disassociate_multicast_group disassociate_wireless_device firmware_update_image firmware_update_role lo_ra_wan name tags" + }, + "AWS::IoTWireless::MulticastGroup": { + "a": "associate_wireless_device description disassociate_wireless_device lo_ra_wan name tags" + }, + "AWS::IoTWireless::NetworkAnalyzerConfiguration": { + "a": "description name tags trace_content wireless_devices wireless_gateways" + }, + "AWS::IoTWireless::PartnerAccount": { + "a": "account_linked partner_account_id partner_type sidewalk sidewalk_response sidewalk_update tags" + }, + "AWS::IoTWireless::ServiceProfile": { + "a": "lo_ra_wan name tags" + }, + "AWS::IoTWireless::TaskDefinition": { + "a": "auto_create_tasks lo_ra_wan_update_gateway_task_entry name tags task_definition_type update" + }, + "AWS::IoTWireless::WirelessDevice": { + "a": "description destination_name last_uplink_received_at lo_ra_wan name positioning tags thing_arn type" + }, + "AWS::IoTWireless::WirelessDeviceImportTask": { + "a": "destination_name sidewalk tags" + }, + "AWS::IoTWireless::WirelessGateway": { + "a": "description last_uplink_received_at lo_ra_wan name tags thing_arn thing_name" + }, + "AWS::KMS::Alias": { + "a": "alias_name target_key_id" + }, + "AWS::KMS::Key": { + "a": "bypass_policy_lockout_safety_check description enable_key_rotation enabled key_policy key_spec key_usage multi_region origin pending_window_in_days rotation_period_in_days tags", + "j": [ + "KeyPolicy" + ] + }, + "AWS::KMS::ReplicaKey": { + "a": "description enabled key_policy pending_window_in_days primary_key_arn tags", + "j": [ + "KeyPolicy" + ] + }, + "AWS::KafkaConnect::Connector": { + "a": "capacity connector_configuration connector_description connector_name kafka_cluster kafka_cluster_client_authentication kafka_cluster_encryption_in_transit kafka_connect_version log_delivery network_type plugins service_execution_role_arn tags worker_configuration", + "m": [ + "ConnectorConfiguration" + ] + }, + "AWS::KafkaConnect::CustomPlugin": { + "a": "content_type description location name tags" + }, + "AWS::KafkaConnect::WorkerConfiguration": { + "a": "description name properties_file_content tags" + }, + "AWS::Kendra::DataSource": { + "a": "custom_document_enrichment_configuration data_source_configuration description index_id language_code name role_arn schedule tags type", + "j": [ + "DataSourceConfiguration.TemplateConfiguration.Template" + ] + }, + "AWS::Kendra::Faq": { + "a": "description file_format index_id language_code name role_arn s3_path tags" + }, + "AWS::Kendra::FeaturedResultsSet": { + "a": "description featured_documents featured_results_set_name index_id query_texts status tags" + }, + "AWS::Kendra::Index": { + "a": "capacity_units description document_metadata_configurations edition name role_arn server_side_encryption_configuration tags user_context_policy user_token_configurations" + }, + "AWS::Kendra::QuerySuggestionsBlockList": { + "a": "description index_id name role_arn source_s3_path tags" + }, + "AWS::Kendra::Thesaurus": { + "a": "description index_id name role_arn source_s3_path tags" + }, + "AWS::KendraRanking::ExecutionPlan": { + "a": "capacity_units description name tags" + }, + "AWS::Kinesis::Channel": { + "a": "channel_name encryption_configuration logging_configuration s3_destination_configuration s3_tables_destination_configuration service_execution_role_arn stream_configuration_list tags" + }, + "AWS::Kinesis::ResourcePolicy": { + "a": "resource_arn resource_policy", + "j": [ + "ResourceArn", + "ResourcePolicy" + ] + }, + "AWS::Kinesis::Stream": { + "a": "desired_shard_level_metrics max_record_size_in_ki_b name record_distribution_strategy retention_period_hours shard_count stream_encryption stream_mode_details tags warm_throughput_mi_bps", + "j": [ + "StreamEncryption.KeyId" + ] + }, + "AWS::Kinesis::StreamConsumer": { + "a": "consumer_name stream_arn tags" + }, + "AWS::KinesisAnalyticsV2::Application": { + "a": "application_configuration application_description application_maintenance_configuration application_mode application_name run_configuration runtime_environment service_execution_role tags", + "m": [ + "ApplicationConfiguration.EnvironmentProperties.PropertyGroups.PropertyMap" + ] + }, + "AWS::KinesisFirehose::DeliveryStream": { + "a": "amazon_open_search_serverless_destination_configuration amazonopensearchservice_destination_configuration database_source_configuration delivery_stream_encryption_configuration_input delivery_stream_name delivery_stream_type direct_put_source_configuration elasticsearch_destination_configuration extended_s3_destination_configuration http_endpoint_destination_configuration iceberg_destination_configuration kinesis_stream_source_configuration msk_source_configuration redshift_destination_configuration s3_destination_configuration snowflake_destination_configuration splunk_destination_configuration tags", + "j": [ + "AmazonOpenSearchServerlessDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "AmazonopensearchserviceDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "ElasticsearchDestinationConfiguration.DomainARN", + "ElasticsearchDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "ExtendedS3DestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "HttpEndpointDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "IcebergDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "RedshiftDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "SnowflakeDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue", + "SplunkDestinationConfiguration.ProcessingConfiguration.Processors.Parameters.ParameterValue" + ], + "m": [ + "ExtendedS3DestinationConfiguration.DataFormatConversionConfiguration.InputFormatConfiguration.Deserializer.OpenXJsonSerDe.ColumnToJsonKeyMappings" + ], + "r": { + "IcebergDestinationConfiguration.s3BackupMode": "s_3_backup_mode" + } + }, + "AWS::KinesisVideo::SignalingChannel": { + "a": "message_ttl_seconds name tags type" + }, + "AWS::KinesisVideo::Stream": { + "a": "data_retention_in_hours device_name kms_key_id media_type name stream_storage_configuration tags" + }, + "AWS::LakeFormation::DataCellsFilter": { + "a": "column_names column_wildcard database_name name row_filter table_catalog_id table_name", + "j": [ + "RowFilter.AllRowsWildcard" + ] + }, + "AWS::LakeFormation::PrincipalPermissions": { + "a": "catalog permissions permissions_with_grant_option principal resource", + "j": [ + "Resource.Table.TableWildcard" + ] + }, + "AWS::LakeFormation::Resource": { + "a": "hybrid_access_enabled resource_arn role_arn use_service_linked_role with_federation" + }, + "AWS::LakeFormation::Tag": { + "a": "catalog_id tag_key tag_values" + }, + "AWS::LakeFormation::TagAssociation": { + "a": "lf_tags resource", + "j": [ + "Resource.Catalog", + "Resource.Table.TableWildcard" + ] + }, + "AWS::Lambda::Alias": { + "a": "description function_name function_version name provisioned_concurrency_config routing_config" + }, + "AWS::Lambda::CapacityProvider": { + "a": "capacity_provider_name capacity_provider_scaling_config instance_requirements kms_key_arn permissions_config propagate_tags tags telemetry_config vpc_config" + }, + "AWS::Lambda::CodeSigningConfig": { + "a": "allowed_publishers code_signing_policies description tags" + }, + "AWS::Lambda::EventInvokeConfig": { + "a": "destination_config function_name maximum_event_age_in_seconds maximum_retry_attempts qualifier" + }, + "AWS::Lambda::EventSourceMapping": { + "a": "amazon_managed_kafka_event_source_config batch_size bisect_batch_on_function_error destination_config document_db_event_source_config enabled event_source_arn filter_criteria function_name function_response_types kms_key_arn logging_config maximum_batching_window_in_seconds maximum_record_age_in_seconds maximum_retry_attempts metrics_config parallelization_factor provisioned_poller_config queues scaling_config self_managed_event_source self_managed_kafka_event_source_config source_access_configurations starting_position starting_position_timestamp tags topics tumbling_window_in_seconds" + }, + "AWS::Lambda::Function": { + "a": "architectures capacity_provider_config code code_signing_config_arn dead_letter_config description durable_config environment ephemeral_storage file_system_configs function_name function_scaling_config handler image_config kms_key_arn layers logging_config memory_size package_type publish_to_latest_published recursive_loop reserved_concurrent_executions role runtime runtime_management_config snap_start tags tenancy_config timeout tracing_config vpc_config", + "m": [ + "Environment.Variables" + ], + "x": [ + "AcceleratorConfig", + "DurableConfig.KMSKeyArn", + "FileSystemConfigs.S3FilesConfig", + "RuntimeConfig" + ] + }, + "AWS::Lambda::LayerVersion": { + "a": "compatible_architectures compatible_runtimes content description layer_name license_info" + }, + "AWS::Lambda::LayerVersionPermission": { + "a": "action layer_version_arn organization_id principal" + }, + "AWS::Lambda::MicrovmImage": { + "a": "additional_os_capabilities base_image_arn base_image_version build_role_arn code_artifact cpu_configurations description egress_network_connectors environment_variables hooks kms_key_identifier logging name resources tags" + }, + "AWS::Lambda::NetworkConnector": { + "a": "configuration name operator_role tags", + "x": [ + "Configuration.VpcEgressConfiguration.ElasticIpConfiguration" + ] + }, + "AWS::Lambda::Permission": { + "a": "action event_source_token function_name function_url_auth_type invoked_via_function_url principal principal_org_id source_account source_arn" + }, + "AWS::Lambda::ResourcePolicy": { + "a": "policy_document resource_arn", + "j": [ + "PolicyDocument", + "ResourceArn" + ] + }, + "AWS::Lambda::Url": { + "a": "auth_type cors invoke_mode qualifier target_function_arn" + }, + "AWS::Lambda::Version": { + "a": "code_sha_256 description function_name function_scaling_config provisioned_concurrency_config runtime_policy" + }, + "AWS::Lambda::WebFunction": { + "a": "function_name tags" + }, + "AWS::Lambda::WebFunctionEndpoint": { + "a": "auth_type description endpoint_name endpoint_type function_name regions revision_weights scaling_config throttle_config", + "m": [ + "RegionalEndpoints" + ] + }, + "AWS::Lambda::WebFunctionRevision": { + "a": "build_config description function_name kms_key_arn service_config", + "m": [ + "ServiceConfig.EnvironmentVariables" + ] + }, + "AWS::LaunchWizard::Deployment": { + "a": "deployment_pattern_name name specifications tags workload_name", + "m": [ + "Specifications" + ] + }, + "AWS::Lex::Bot": { + "a": "auto_build_bot_locales bot_file_s3_location bot_locales bot_tags data_privacy description idle_session_ttl_in_seconds name role_arn test_bot_alias_settings test_bot_alias_tags", + "m": [ + "BotLocales.Intents.IntentConfirmationSetting.PromptSpecification.PromptAttemptsSpecification", + "BotLocales.Intents.Slots.ValueElicitationSetting.PromptSpecification.PromptAttemptsSpecification" + ], + "x": [ + "BotLocales.AudioFillerSettings", + "BotLocales.CustomVocabulary.CustomVocabularyItems.DisplayAs", + "BotLocales.GenerativeAISettings", + "BotLocales.Intents.BedrockAgentIntentConfiguration", + "BotLocales.Intents.DisplayName", + "BotLocales.Intents.FulfillmentCodeHook.IsActive", + "BotLocales.Intents.FulfillmentCodeHook.PostFulfillmentStatusSpecification.FailureConditional", + "BotLocales.Intents.FulfillmentCodeHook.PostFulfillmentStatusSpecification.FailureNextStep", + "BotLocales.Intents.FulfillmentCodeHook.PostFulfillmentStatusSpecification.SuccessConditional", + "BotLocales.Intents.FulfillmentCodeHook.PostFulfillmentStatusSpecification.SuccessNextStep", + "BotLocales.Intents.FulfillmentCodeHook.PostFulfillmentStatusSpecification.TimeoutConditional", + "BotLocales.Intents.FulfillmentCodeHook.PostFulfillmentStatusSpecification.TimeoutNextStep", + "BotLocales.Intents.InitialResponseSetting", + "BotLocales.Intents.IntentClosingSetting.Conditional", + "BotLocales.Intents.IntentClosingSetting.NextStep", + "BotLocales.Intents.IntentConfirmationSetting.CodeHook", + "BotLocales.Intents.IntentConfirmationSetting.ConfirmationConditional", + "BotLocales.Intents.IntentConfirmationSetting.ConfirmationNextStep", + "BotLocales.Intents.IntentConfirmationSetting.ConfirmationResponse", + "BotLocales.Intents.IntentConfirmationSetting.DeclinationConditional", + "BotLocales.Intents.IntentConfirmationSetting.DeclinationNextStep", + "BotLocales.Intents.IntentConfirmationSetting.ElicitationCodeHook", + "BotLocales.Intents.IntentConfirmationSetting.FailureConditional", + "BotLocales.Intents.IntentConfirmationSetting.FailureNextStep", + "BotLocales.Intents.IntentConfirmationSetting.FailureResponse", + "BotLocales.Intents.QInConnectIntentConfiguration", + "BotLocales.Intents.QnAIntentConfiguration", + "BotLocales.Intents.Slots.SubSlotSetting", + "BotLocales.Intents.Slots.ValueElicitationSetting.SlotCaptureSetting", + "BotLocales.SlotTypes.CompositeSlotTypeSetting", + "BotLocales.SpeechDetectionSensitivity", + "BotLocales.SpeechRecognitionSettings", + "BotLocales.UnifiedSpeechSettings", + "BotMembers", + "BotType", + "ErrorLogSettings", + "Replication" + ] + }, + "AWS::Lex::BotAlias": { + "a": "bot_alias_locale_settings bot_alias_name bot_alias_tags bot_id bot_version conversation_log_settings description sentiment_analysis_settings" + }, + "AWS::Lex::BotVersion": { + "a": "bot_id bot_version_locale_specification description" + }, + "AWS::Lex::ResourcePolicy": { + "a": "policy resource_arn", + "j": [ + "Policy" + ] + }, + "AWS::LicenseManager::Grant": { + "a": "allowed_operations grant_name home_region license_arn principals status tags" + }, + "AWS::LicenseManager::License": { + "a": "beneficiary consumption_configuration entitlements home_region issuer license_metadata license_name product_name product_sku status tags validity" + }, + "AWS::LicenseManager::LicenseAssetGroup": { + "a": "associated_license_asset_ruleset_ar_ns description license_asset_group_configurations name properties tags" + }, + "AWS::LicenseManager::LicenseAssetRuleSet": { + "a": "description name rules tags" + }, + "AWS::LicenseManager::LicenseConfiguration": { + "a": "description disassociate_when_not_found license_count license_count_hard_limit license_counting_type license_expiry license_rules name product_information_list tags" + }, + "AWS::LicenseManager::ReportGenerator": { + "a": "description report_context report_frequency report_generator_name report_type tags" + }, + "AWS::LicenseManagerLinuxSubscriptions::SubscriptionProvider": { + "a": "secret_arn subscription_provider_source tags" + }, + "AWS::LicenseManagerUserSubscriptions::LicenseServerEndpoint": { + "a": "identity_provider_arn license_server_settings tags" + }, + "AWS::Lightsail::Alarm": { + "a": "alarm_name comparison_operator contact_protocols datapoints_to_alarm evaluation_periods metric_name monitored_resource_name notification_enabled notification_triggers threshold treat_missing_data" + }, + "AWS::Lightsail::Bucket": { + "a": "access_rules bucket_name bundle_id object_versioning read_only_access_accounts resources_receiving_access tags" + }, + "AWS::Lightsail::Certificate": { + "a": "certificate_name domain_name subject_alternative_names tags" + }, + "AWS::Lightsail::ContactMethod": { + "a": "contact_endpoint protocol" + }, + "AWS::Lightsail::Container": { + "a": "container_service_deployment is_disabled power private_registry_access public_domain_names scale service_name tags" + }, + "AWS::Lightsail::Database": { + "a": "availability_zone backup_retention ca_certificate_identifier master_database_name master_user_password master_username preferred_backup_window preferred_maintenance_window publicly_accessible relational_database_blueprint_id relational_database_bundle_id relational_database_name relational_database_parameters rotate_master_user_password tags" + }, + "AWS::Lightsail::DatabaseSnapshot": { + "a": "relational_database_name relational_database_snapshot_name tags" + }, + "AWS::Lightsail::Disk": { + "a": "add_ons availability_zone disk_name location size_in_gb tags" + }, + "AWS::Lightsail::DiskSnapshot": { + "a": "disk_name disk_snapshot_name tags" + }, + "AWS::Lightsail::Distribution": { + "a": "bundle_id cache_behavior_settings cache_behaviors certificate_name default_cache_behavior distribution_name ip_address_type is_enabled origin tags" + }, + "AWS::Lightsail::Domain": { + "a": "domain_entries domain_name tags" + }, + "AWS::Lightsail::Instance": { + "a": "add_ons availability_zone blueprint_id bundle_id hardware instance_name key_pair_name location networking state tags user_data" + }, + "AWS::Lightsail::InstanceSnapshot": { + "a": "instance_name instance_snapshot_name tags" + }, + "AWS::Lightsail::KeyPair": { + "a": "key_pair_name tags" + }, + "AWS::Lightsail::LoadBalancer": { + "a": "attached_instances health_check_path instance_port ip_address_type load_balancer_name session_stickiness_enabled session_stickiness_lb_cookie_duration_seconds tags tls_policy_name" + }, + "AWS::Lightsail::LoadBalancerTlsCertificate": { + "a": "certificate_alternative_names certificate_domain_name certificate_name https_redirection_enabled is_attached load_balancer_name" + }, + "AWS::Lightsail::StaticIp": { + "a": "attached_to static_ip_name" + }, + "AWS::Location::APIKey": { + "a": "description expire_time force_delete force_update key_name no_expiry restrictions tags" + }, + "AWS::Location::GeofenceCollection": { + "a": "collection_name description kms_key_id pricing_plan pricing_plan_data_source tags" + }, + "AWS::Location::Map": { + "a": "configuration description map_name pricing_plan tags" + }, + "AWS::Location::PlaceIndex": { + "a": "data_source data_source_configuration description index_name pricing_plan tags" + }, + "AWS::Location::RouteCalculator": { + "a": "calculator_name data_source description pricing_plan tags" + }, + "AWS::Location::Tracker": { + "a": "description event_bridge_enabled kms_key_enable_geospatial_queries kms_key_id position_filtering pricing_plan pricing_plan_data_source tags tracker_name" + }, + "AWS::Location::TrackerConsumer": { + "a": "consumer_arn tracker_name" + }, + "AWS::Logs::AccountPolicy": { + "a": "policy_document policy_name policy_type scope selection_criteria" + }, + "AWS::Logs::Delivery": { + "a": "delivery_destination_arn delivery_source_name field_delimiter record_fields s3_enable_hive_compatible_path s3_suffix_path tags" + }, + "AWS::Logs::DeliveryDestination": { + "a": "delivery_destination_policy delivery_destination_type destination_resource_arn name output_format tags", + "j": [ + "DeliveryDestinationPolicy.DeliveryDestinationPolicy" + ] + }, + "AWS::Logs::DeliverySource": { + "a": "delivery_source_configuration log_type name resource_arn tags", + "m": [ + "DeliverySourceConfiguration" + ] + }, + "AWS::Logs::Destination": { + "a": "destination_name destination_policy role_arn tags target_arn" + }, + "AWS::Logs::Integration": { + "a": "integration_name integration_type resource_config" + }, + "AWS::Logs::LogAnomalyDetector": { + "a": "account_id anomaly_visibility_time detector_name evaluation_frequency filter_pattern kms_key_id log_group_arn_list" + }, + "AWS::Logs::LogGroup": { + "a": "data_protection_policy kms_key_id log_group_class log_group_name retention_in_days tags", + "j": [ + "DataProtectionPolicy" + ], + "x": [ + "BearerTokenAuthenticationEnabled", + "DeletionProtectionEnabled", + "FieldIndexPolicies", + "ResourcePolicyDocument" + ] + }, + "AWS::Logs::LogStream": { + "a": "log_group_name log_stream_name" + }, + "AWS::Logs::MetricFilter": { + "a": "apply_on_transformed_logs emit_system_field_dimensions field_selection_criteria filter_name filter_pattern log_group_name metric_transformations" + }, + "AWS::Logs::QueryDefinition": { + "a": "log_group_names name parameters query_language query_string" + }, + "AWS::Logs::ResourcePolicy": { + "a": "policy_document policy_name", + "j": [ + "PolicyDocument" + ] + }, + "AWS::Logs::ScheduledQuery": { + "a": "description destination_configuration execution_role_arn log_group_identifiers name query_language query_string schedule_end_time schedule_expression schedule_start_time start_time_offset state tags timezone" + }, + "AWS::Logs::StorageTierPolicy": { + "a": "storage_tier" + }, + "AWS::Logs::SubscriptionFilter": { + "a": "apply_on_transformed_logs destination_arn distribution emit_system_fields field_selection_criteria filter_name filter_pattern log_group_name role_arn" + }, + "AWS::LookoutEquipment::InferenceScheduler": { + "a": "data_delay_offset_in_minutes data_input_configuration data_output_configuration data_upload_frequency inference_scheduler_name model_name role_arn server_side_kms_key_id tags" + }, + "AWS::M2::Application": { + "a": "definition description engine_type kms_key_id name role_arn tags", + "m": [ + "Tags" + ] + }, + "AWS::M2::Deployment": { + "a": "application_id application_version environment_id" + }, + "AWS::M2::Environment": { + "a": "description engine_type engine_version high_availability_config instance_type kms_key_id name network_type preferred_maintenance_window publicly_accessible security_group_ids storage_configurations subnet_ids tags", + "m": [ + "Tags" + ] + }, + "AWS::MGN::Application": { + "a": "description name tags" + }, + "AWS::MGN::Connector": { + "a": "name ssm_command_config ssm_instance_id tags" + }, + "AWS::MGN::NetworkMigrationDefinition": { + "a": "description name scope_tags source_configurations tags target_deployment target_network target_s3_configuration", + "m": [ + "ScopeTags" + ] + }, + "AWS::MGN::ReplicationConfigurationTemplate": { + "a": "associate_default_security_group bandwidth_throttling create_public_ip data_plane_routing default_large_staging_disk_type ebs_encryption ebs_encryption_key_arn internet_protocol replication_server_instance_type replication_servers_security_groups_i_ds staging_area_subnet_id staging_area_tags store_snapshot_on_local_zone tags use_dedicated_replication_server use_fips_endpoint", + "m": [ + "StagingAreaTags" + ] + }, + "AWS::MGN::Wave": { + "a": "description name tags" + }, + "AWS::MPA::IdentitySource": { + "a": "identity_source_parameters tags" + }, + "AWS::MSK::BatchScramSecret": { + "a": "cluster_arn secret_arn_list" + }, + "AWS::MSK::Channel": { + "a": "channel_name cluster_arn encryption_configuration iceberg_destination_configuration logging_info s3_destination_configuration tags topic_configuration_list", + "m": [ + "Tags" + ] + }, + "AWS::MSK::Cluster": { + "a": "broker_node_group_info client_authentication cluster_name configuration_info encryption_info enhanced_monitoring kafka_version logging_info number_of_broker_nodes open_monitoring rebalancing storage_mode tags zookeeper_access", + "m": [ + "Tags" + ], + "x": [ + "BrokerNodeGroupInfo.TopicReassignment" + ] + }, + "AWS::MSK::ClusterPolicy": { + "a": "cluster_arn policy", + "j": [ + "Policy" + ] + }, + "AWS::MSK::Configuration": { + "a": "description kafka_versions_list latest_revision name server_properties" + }, + "AWS::MSK::Replicator": { + "a": "description kafka_clusters log_delivery replication_info_list replicator_name service_execution_role_arn tags" + }, + "AWS::MSK::ServerlessCluster": { + "a": "client_authentication cluster_name tags vpc_configs", + "m": [ + "Tags" + ] + }, + "AWS::MSK::Topic": { + "a": "cluster_arn configs partition_count replication_factor topic_name" + }, + "AWS::MSK::VpcConnection": { + "a": "authentication client_subnets security_groups tags target_cluster_arn vpc_id", + "m": [ + "Tags" + ] + }, + "AWS::MWAA::Environment": { + "a": "airflow_configuration_options airflow_version dag_s3_path endpoint_management environment_class execution_role_arn kms_key logging_configuration max_webservers max_workers min_webservers min_workers name network_configuration plugins_s3_object_version plugins_s3_path requirements_s3_object_version requirements_s3_path schedulers source_bucket_arn startup_script_s3_object_version startup_script_s3_path tags webserver_access_mode weekly_maintenance_window_start worker_replacement_strategy", + "j": [ + "AirflowConfigurationOptions", + "Tags" + ] + }, + "AWS::MWAAServerless::Workflow": { + "a": "code definition_s3_location description encryption_configuration logging_configuration name network_configuration role_arn tags trigger_mode", + "m": [ + "Tags" + ], + "x": [ + "Environment" + ] + }, + "AWS::Macie::AllowList": { + "a": "criteria description name tags" + }, + "AWS::Macie::CustomDataIdentifier": { + "a": "description ignore_words keywords maximum_match_distance name regex tags" + }, + "AWS::Macie::FindingsFilter": { + "a": "action description finding_criteria name position tags", + "m": [ + "FindingCriteria.Criterion" + ] + }, + "AWS::Macie::Member": { + "a": "account_id email tags" + }, + "AWS::Macie::Session": { + "a": "finding_publishing_frequency status" + }, + "AWS::ManagedBlockchain::Accessor": { + "a": "accessor_type network_type tags" + }, + "AWS::MediaConnect::Bridge": { + "a": "egress_gateway_bridge ingress_gateway_bridge name outputs placement_arn source_failover_config sources" + }, + "AWS::MediaConnect::BridgeOutput": { + "a": "bridge_arn name network_output" + }, + "AWS::MediaConnect::BridgeSource": { + "a": "bridge_arn flow_source name network_source" + }, + "AWS::MediaConnect::DestinationEndpoint": { + "a": "configuration description region_name tags" + }, + "AWS::MediaConnect::Flow": { + "a": "availability_zone encoding_config flow_size maintenance media_streams name ndi_config source source_failover_config source_monitoring_config tags vpc_interfaces", + "x": [ + "Source.NdiSourceSettings.AudioReferenceLevel", + "Source.RtmpPushDetails", + "Source.RtmpPushSettings" + ] + }, + "AWS::MediaConnect::FlowEntitlement": { + "a": "data_transfer_subscriber_fee_percent description encryption entitlement_status flow_arn name subscribers tags" + }, + "AWS::MediaConnect::FlowMediaStream": { + "a": "attributes clock_rate description flow_arn media_stream_id media_stream_name media_stream_type tags video_format" + }, + "AWS::MediaConnect::FlowOutput": { + "a": "cidr_allow_list description destination encryption flow_arn max_latency media_stream_output_configurations min_latency name ndi_audio_reference_level ndi_output_timecode_source ndi_program_name ndi_speed_hq_quality output_status port protocol remote_id router_integration_state router_integration_transit_encryption smoothing_latency stream_id tags vpc_interface_attachment", + "x": [ + "RtmpPushSettings" + ] + }, + "AWS::MediaConnect::FlowSource": { + "a": "decryption description entitlement_arn flow_arn gateway_bridge_source ingest_port max_bitrate max_latency min_latency name protocol sender_control_port sender_ip_address source_listener_address source_listener_port stream_id tags vpc_interface_name whitelist_cidr", + "x": [ + "RtmpPushDetails", + "RtmpPushSettings" + ] + }, + "AWS::MediaConnect::FlowVpcInterface": { + "a": "flow_arn name role_arn security_group_ids subnet_id tags" + }, + "AWS::MediaConnect::Gateway": { + "a": "egress_cidr_blocks name networks" + }, + "AWS::MediaConnect::RouterInput": { + "a": "availability_zone configuration content_quality_analysis_configuration maintenance_configuration maximum_bitrate name region_name routing_scope tags tier transit_encryption", + "x": [ + "StreamDetails" + ] + }, + "AWS::MediaConnect::RouterNetworkInterface": { + "a": "configuration name region_name tags" + }, + "AWS::MediaConnect::RouterOutput": { + "a": "availability_zone configuration fabric_configuration maintenance_configuration maximum_bitrate name region_name routing_scope tags tier" + }, + "AWS::MediaConnect::SourceEndpoint": { + "a": "configuration description region_name tags" + }, + "AWS::MediaConvert::CertificateAssociation": { + "a": "arn" + }, + "AWS::MediaConvert::JobTemplate": { + "a": "acceleration_settings category description hop_destinations name priority queue settings_json status_update_interval tags", + "j": [ + "SettingsJson", + "Tags" + ] + }, + "AWS::MediaConvert::Preset": { + "a": "category description name settings_json tags", + "j": [ + "SettingsJson", + "Tags" + ] + }, + "AWS::MediaConvert::Queue": { + "a": "concurrent_jobs description maximum_concurrent_feeds name pricing_plan status tags", + "j": [ + "Tags" + ] + }, + "AWS::MediaLive::ChannelPlacementGroup": { + "a": "cluster_id name nodes tags" + }, + "AWS::MediaLive::CloudWatchAlarmTemplate": { + "a": "comparison_operator datapoints_to_alarm description evaluation_periods group_identifier metric_name name period statistic tags target_resource_type threshold treat_missing_data", + "m": [ + "Tags" + ] + }, + "AWS::MediaLive::CloudWatchAlarmTemplateGroup": { + "a": "description name tags", + "m": [ + "Tags" + ] + }, + "AWS::MediaLive::Cluster": { + "a": "cluster_type instance_role_arn name network_settings tags" + }, + "AWS::MediaLive::EventBridgeRuleTemplate": { + "a": "description event_targets event_type group_identifier name tags", + "m": [ + "Tags" + ] + }, + "AWS::MediaLive::EventBridgeRuleTemplateGroup": { + "a": "description name tags", + "m": [ + "Tags" + ] + }, + "AWS::MediaLive::Input": { + "a": "destinations input_devices input_network_location input_security_groups media_connect_flows multicast_settings name role_arn router_settings sdi_sources smpte_2110_receiver_group_settings sources srt_settings tags type vpc", + "m": [ + "Tags" + ] + }, + "AWS::MediaLive::InputSecurityGroup": { + "a": "tags whitelist_rules", + "m": [ + "Tags" + ] + }, + "AWS::MediaLive::Multiplex": { + "a": "availability_zones destinations multiplex_settings name tags" + }, + "AWS::MediaLive::Multiplexprogram": { + "a": "multiplex_id multiplex_program_settings packet_identifiers_map pipeline_details preferred_channel_pipeline program_name" + }, + "AWS::MediaLive::Network": { + "a": "ip_pools name routes tags" + }, + "AWS::MediaLive::Node": { + "a": "cluster_id name node_interface_mappings role sdi_source_mappings tags" + }, + "AWS::MediaLive::SdiSource": { + "a": "mode name tags type" + }, + "AWS::MediaLive::SignalMap": { + "a": "cloudwatch_alarm_template_group_identifiers description discovery_entry_point_arn event_bridge_rule_template_group_identifiers force_rediscovery name tags", + "m": [ + "FailedMediaResourceMap", + "MediaResourceMap", + "Tags" + ] + }, + "AWS::MediaPackage::Asset": { + "a": "asset_id egress_endpoints packaging_group_id resource_id source_arn source_role_arn tags" + }, + "AWS::MediaPackage::PackagingConfiguration": { + "a": "cmaf_package dash_package hls_package mss_package packaging_configuration_id packaging_group_id tags" + }, + "AWS::MediaPackage::PackagingGroup": { + "a": "authorization egress_access_logs packaging_group_id tags" + }, + "AWS::MediaPackageV2::Channel": { + "a": "channel_group_name channel_name description input_switch_configuration input_type multiview_configuration output_header_configuration output_locking_mode tags" + }, + "AWS::MediaPackageV2::ChannelGroup": { + "a": "channel_group_name description tags" + }, + "AWS::MediaPackageV2::ChannelPolicy": { + "a": "channel_group_name channel_name policy", + "j": [ + "Policy" + ] + }, + "AWS::MediaPackageV2::OriginEndpoint": { + "a": "channel_group_name channel_name container_type dash_manifests description force_endpoint_error_configuration hls_manifests low_latency_hls_manifests mss_manifests origin_endpoint_name segment startover_window_seconds stream_name_output_mode tags uri_separator", + "x": [ + "DashManifests.BandwidthReportingMode" + ] + }, + "AWS::MediaPackageV2::OriginEndpointPolicy": { + "a": "cdn_auth_configuration channel_group_name channel_name origin_endpoint_name policy", + "j": [ + "Policy" + ] + }, + "AWS::MediaTailor::Channel": { + "a": "audiences channel_name filler_slate log_configuration outputs playback_mode tags tier time_shift_configuration" + }, + "AWS::MediaTailor::ChannelPolicy": { + "a": "channel_name policy", + "j": [ + "Policy" + ] + }, + "AWS::MediaTailor::Function": { + "a": "aws_service_request_configuration concurrent_executor_configuration custom_output_configuration description function_id function_type http_request_configuration sequential_executor_configuration tags vast_request_configuration", + "m": [ + "AwsServiceRequestConfiguration.Headers", + "AwsServiceRequestConfiguration.Output", + "ConcurrentExecutorConfiguration.Output", + "CustomOutputConfiguration.Output", + "HttpRequestConfiguration.Headers", + "HttpRequestConfiguration.Output", + "SequentialExecutorConfiguration.Output", + "VastRequestConfiguration.Headers", + "VastRequestConfiguration.Output" + ] + }, + "AWS::MediaTailor::LiveSource": { + "a": "http_package_configurations live_source_name source_location_name tags" + }, + "AWS::MediaTailor::PrefetchSchedule": { + "a": "consumption name playback_configuration_name recurring_prefetch_configuration retrieval schedule_type stream_id tags", + "m": [ + "RecurringPrefetchConfiguration.RecurringRetrieval.DynamicVariables", + "Retrieval.DynamicVariables" + ] + }, + "AWS::MediaTailor::Program": { + "a": "ad_breaks audience_media channel_name live_source_name program_name schedule_configuration source_location_name vod_source_name" + }, + "AWS::MediaTailor::SourceLocation": { + "a": "access_configuration default_segment_delivery_configuration http_configuration segment_delivery_configurations source_location_name tags" + }, + "AWS::MediaTailor::VodSource": { + "a": "http_package_configurations source_location_name tags vod_source_name" + }, + "AWS::MemoryDB::ACL": { + "a": "acl_name tags user_names" + }, + "AWS::MemoryDB::Cluster": { + "a": "acl_name auto_minor_version_upgrade cluster_endpoint cluster_name data_tiering description engine engine_version final_snapshot_name ip_discovery kms_key_id maintenance_window multi_region_cluster_name network_type node_type num_replicas_per_shard num_shards parameter_group_name port security_group_ids snapshot_arns snapshot_name snapshot_retention_limit snapshot_window sns_topic_arn sns_topic_status subnet_group_name tags tls_enabled" + }, + "AWS::MemoryDB::MultiRegionCluster": { + "a": "description engine engine_version multi_region_cluster_name_suffix multi_region_parameter_group_name node_type num_shards tags tls_enabled update_strategy" + }, + "AWS::MemoryDB::ParameterGroup": { + "a": "description family parameter_group_name parameters tags", + "j": [ + "Parameters" + ] + }, + "AWS::MemoryDB::Snapshot": { + "a": "cluster_name kms_key_id snapshot_name tags" + }, + "AWS::MemoryDB::SubnetGroup": { + "a": "description subnet_group_name subnet_ids tags" + }, + "AWS::MemoryDB::User": { + "a": "access_string authentication_mode tags user_name" + }, + "AWS::Neptune::DBCluster": { + "a": "associated_roles availability_zones backup_retention_period copy_tags_to_snapshot db_cluster_identifier db_cluster_parameter_group_name db_instance_parameter_group_name db_port db_subnet_group_name deletion_protection enable_cloudwatch_logs_exports engine_version global_cluster_identifier iam_auth_enabled kms_key_id network_type preferred_backup_window preferred_maintenance_window restore_to_time restore_type serverless_scaling_configuration snapshot_identifier source_db_cluster_identifier storage_encrypted tags use_latest_restorable_time vpc_security_group_ids" + }, + "AWS::Neptune::DBClusterParameterGroup": { + "a": "description family name parameters tags", + "j": [ + "Parameters" + ] + }, + "AWS::Neptune::DBInstance": { + "a": "allow_major_version_upgrade auto_minor_version_upgrade availability_zone db_cluster_identifier db_instance_class db_instance_identifier db_parameter_group_name db_snapshot_identifier db_subnet_group_name preferred_maintenance_window publicly_accessible tags" + }, + "AWS::Neptune::DBParameterGroup": { + "a": "description family name parameters tags", + "j": [ + "Parameters" + ] + }, + "AWS::Neptune::DBSubnetGroup": { + "a": "db_subnet_group_description db_subnet_group_name subnet_ids tags" + }, + "AWS::Neptune::EventSubscription": { + "a": "enabled event_categories sns_topic_arn source_ids source_type subscription_name tags" + }, + "AWS::Neptune::GlobalCluster": { + "a": "deletion_protection engine engine_version global_cluster_identifier source_db_cluster_identifier storage_encrypted tags" + }, + "AWS::NeptuneGraph::Graph": { + "a": "deletion_protection graph_name import_task kms_key_identifier provisioned_memory public_connectivity replica_count tags vector_search_configuration" + }, + "AWS::NeptuneGraph::GraphSnapshot": { + "a": "graph_identifier snapshot_name tags" + }, + "AWS::NeptuneGraph::PrivateGraphEndpoint": { + "a": "graph_identifier security_group_ids subnet_ids vpc_id" + }, + "AWS::NetworkFirewall::ContainerAssociation": { + "a": "container_association_name container_monitoring_configurations description tags type" + }, + "AWS::NetworkFirewall::Firewall": { + "a": "availability_zone_change_protection availability_zone_mappings delete_protection description enabled_analysis_types firewall_name firewall_policy_arn firewall_policy_change_protection nat_gateway_mappings no_source_preservation proxy_settings subnet_change_protection subnet_mappings tags transit_gateway_id vpc_endpoint vpc_id" + }, + "AWS::NetworkFirewall::FirewallPolicy": { + "a": "description firewall_policy firewall_policy_name tags", + "m": [ + "FirewallPolicy.PolicyVariables.RuleVariables" + ], + "x": [ + "FirewallPolicy.Route53ResolvedIPValidation" + ] + }, + "AWS::NetworkFirewall::LoggingConfiguration": { + "a": "enable_monitoring_dashboard firewall_arn firewall_name logging_configuration", + "m": [ + "LoggingConfiguration.LogDestinationConfigs.LogDestination" + ] + }, + "AWS::NetworkFirewall::RuleGroup": { + "a": "capacity description rule_group rule_group_name summary_configuration tags type", + "m": [ + "RuleGroup.ReferenceSets.IPSetReferences", + "RuleGroup.RuleVariables.IPSets", + "RuleGroup.RuleVariables.PortSets" + ] + }, + "AWS::NetworkFirewall::TLSInspectionConfiguration": { + "a": "description tags tls_inspection_configuration tls_inspection_configuration_name" + }, + "AWS::NetworkFirewall::VpcEndpointAssociation": { + "a": "description firewall_arn subnet_mapping tags vpc_id" + }, + "AWS::NetworkFlowMonitor::Monitor": { + "a": "local_resources monitor_name remote_resources scope_arn tags" + }, + "AWS::NetworkFlowMonitor::Scope": { + "a": "tags targets" + }, + "AWS::NetworkManager::ConnectAttachment": { + "a": "core_network_id edge_location nat_gateway_rules nat_gateway_support network_function_group_name options routing_policy_label tags transport_attachment_id" + }, + "AWS::NetworkManager::ConnectPeer": { + "a": "bgp_options connect_attachment_id core_network_address inside_cidr_blocks peer_address subnet_arn tags" + }, + "AWS::NetworkManager::CoreNetwork": { + "a": "description global_network_id policy_document tags", + "j": [ + "PolicyDocument" + ] + }, + "AWS::NetworkManager::CoreNetworkPrefixListAssociation": { + "a": "core_network_id prefix_list_alias prefix_list_arn" + }, + "AWS::NetworkManager::CustomerGatewayAssociation": { + "a": "customer_gateway_arn device_id global_network_id link_id" + }, + "AWS::NetworkManager::Device": { + "a": "aws_location description global_network_id location model serial_number site_id tags type vendor" + }, + "AWS::NetworkManager::DirectConnectGatewayAttachment": { + "a": "core_network_id direct_connect_gateway_arn edge_locations nat_gateway_rules nat_gateway_support nat_system_route_support routing_policy_label tags" + }, + "AWS::NetworkManager::GlobalNetwork": { + "a": "created_at description state tags" + }, + "AWS::NetworkManager::Link": { + "a": "bandwidth description global_network_id provider_name site_id tags type", + "x": [ + "Provider" + ] + }, + "AWS::NetworkManager::LinkAssociation": { + "a": "device_id global_network_id link_id" + }, + "AWS::NetworkManager::Site": { + "a": "description global_network_id location tags" + }, + "AWS::NetworkManager::SiteToSiteVpnAttachment": { + "a": "core_network_id nat_gateway_rules nat_gateway_support nat_system_route_support network_function_group_name routing_policy_label tags vpn_connection_arn" + }, + "AWS::NetworkManager::TransitGatewayPeering": { + "a": "core_network_id tags transit_gateway_arn" + }, + "AWS::NetworkManager::TransitGatewayRegistration": { + "a": "global_network_id transit_gateway_arn" + }, + "AWS::NetworkManager::TransitGatewayRouteTableAttachment": { + "a": "network_function_group_name peering_id routing_policy_label tags transit_gateway_route_table_arn" + }, + "AWS::NetworkManager::VpcAttachment": { + "a": "core_network_id nat_gateway_rules nat_gateway_support options routing_policy_label subnet_arns tags vpc_arn" + }, + "AWS::NetworkMonitor::Monitor": { + "a": "aggregation_period monitor_name tags" + }, + "AWS::NetworkMonitor::Probe": { + "a": "destination destination_port monitor_name packet_size protocol source_arn tags" + }, + "AWS::NetworkSecurityManager::Deployment": { + "a": "associated_policy_list associated_scope_list deployment_configuration deployment_description deployment_name tags" + }, + "AWS::NetworkSecurityManager::Policy": { + "a": "associated_template_and_rule_list firewall_type policy_configuration policy_description policy_name priority tags", + "x": [ + "PolicyConfiguration.IgwFirewallConfig" + ] + }, + "AWS::NetworkSecurityManager::Rule": { + "a": "configuration firewall_type rule_description rule_name rule_type tags" + }, + "AWS::NetworkSecurityManager::Scope": { + "a": "scope_configuration scope_description scope_name tags", + "x": [ + "SpecializedScopeType" + ] + }, + "AWS::NetworkSecurityManager::Template": { + "a": "associated_rule_list firewall_type tags template_description template_name" + }, + "AWS::Notifications::ChannelAssociation": { + "a": "arn notification_configuration_arn" + }, + "AWS::Notifications::EventRule": { + "a": "event_pattern event_type notification_configuration_arn regions source", + "m": [ + "StatusSummaryByRegion" + ] + }, + "AWS::Notifications::ManagedNotificationAccountContactAssociation": { + "a": "contact_identifier is_sensitive_events_subscribed managed_notification_configuration_arn" + }, + "AWS::Notifications::ManagedNotificationAdditionalChannelAssociation": { + "a": "channel_arn is_sensitive_events_subscribed managed_notification_configuration_arn" + }, + "AWS::Notifications::NotificationConfiguration": { + "a": "aggregation_duration description name tags" + }, + "AWS::Notifications::NotificationHub": { + "a": "region" + }, + "AWS::Notifications::OrganizationalUnitAssociation": { + "a": "notification_configuration_arn organizational_unit_id" + }, + "AWS::NotificationsContacts::EmailContact": { + "a": "email_address name tags" + }, + "AWS::ODB::CloudAutonomousVmCluster": { + "a": "autonomous_data_storage_size_in_t_bs cloud_exadata_infrastructure_id cpu_core_count_per_node db_servers description display_name iam_roles is_mtls_enabled_vm_cluster license_model maintenance_window memory_per_oracle_compute_unit_in_g_bs odb_network_id scan_listener_port_non_tls scan_listener_port_tls tags time_zone total_container_databases" + }, + "AWS::ODB::CloudExadataInfrastructure": { + "a": "availability_zone availability_zone_id compute_count customer_contacts_to_send_to_oci database_server_type display_name maintenance_window shape storage_count storage_server_type tags" + }, + "AWS::ODB::CloudVmCluster": { + "a": "cloud_exadata_infrastructure_id cluster_name cpu_core_count data_collection_options data_storage_size_in_t_bs db_node_storage_size_in_g_bs db_nodes db_servers display_name gi_version hostname iam_roles is_local_backup_enabled is_sparse_diskgroup_enabled license_model memory_size_in_g_bs odb_network_id scan_listener_port_tcp ssh_public_keys system_version tags time_zone" + }, + "AWS::ODB::OdbNetwork": { + "a": "availability_zone availability_zone_id backup_subnet_cidr client_subnet_cidr cross_region_s3_restore_sources custom_domain_name default_dns_prefix delete_associated_resources display_name kms_access kms_policy_document s3_access s3_policy_document sts_access sts_policy_document tags zero_etl_access", + "r": { + "Ec2PlacementGroupIds": "ec_2_placement_group_ids" + } + }, + "AWS::ODB::OdbPeeringConnection": { + "a": "additional_peer_network_cidrs display_name odb_network_id peer_network_id peer_network_route_table_ids tags" + }, + "AWS::OSIS::Pipeline": { + "a": "buffer_options encryption_at_rest_options log_publishing_options max_units min_units pipeline_configuration_body pipeline_name pipeline_role_arn resource_policy tags vpc_options", + "j": [ + "ResourcePolicy.Policy" + ] + }, + "AWS::OSIS::PipelineEndpoint": { + "a": "pipeline_arn vpc_options" + }, + "AWS::Oam::Link": { + "a": "label_template link_configuration resource_types sink_identifier tags", + "m": [ + "Tags" + ] + }, + "AWS::Oam::Sink": { + "a": "name policy tags", + "j": [ + "Policy" + ], + "m": [ + "Tags" + ] + }, + "AWS::ObservabilityAdmin::DatasetIntegration": { + "a": "role_arn tags" + }, + "AWS::ObservabilityAdmin::OrganizationCentralizationRule": { + "a": "rule rule_name tags" + }, + "AWS::ObservabilityAdmin::OrganizationTelemetryRule": { + "a": "rule rule_name tags" + }, + "AWS::ObservabilityAdmin::S3TableIntegration": { + "a": "encryption log_sources role_arn tags" + }, + "AWS::ObservabilityAdmin::TelemetryEnrichment": { + "a": "scope" + }, + "AWS::ObservabilityAdmin::TelemetryRule": { + "a": "rule rule_name tags" + }, + "AWS::Omics::AnnotationStore": { + "a": "description name reference sse_config store_format store_options tags", + "m": [ + "Tags" + ] + }, + "AWS::Omics::Configuration": { + "a": "description name run_configurations tags", + "m": [ + "Tags" + ] + }, + "AWS::Omics::ReferenceStore": { + "a": "description name sse_config tags", + "m": [ + "Tags" + ] + }, + "AWS::Omics::RunCache": { + "a": "cache_behavior cache_bucket_owner_id cache_s3_location description name tags" + }, + "AWS::Omics::RunGroup": { + "a": "max_cpus max_duration max_gpus max_runs name tags", + "m": [ + "Tags" + ] + }, + "AWS::Omics::SequenceStore": { + "a": "access_log_location description e_tag_algorithm_family fallback_location name propagated_set_level_tags s3_access_policy sse_config tags", + "j": [ + "S3AccessPolicy" + ], + "m": [ + "Tags" + ] + }, + "AWS::Omics::VariantStore": { + "a": "description name reference sse_config tags", + "m": [ + "Tags" + ] + }, + "AWS::Omics::Workflow": { + "a": "accelerators definition_uri description engine main name parameter_template storage_capacity storage_type tags", + "m": [ + "ParameterTemplate", + "Tags" + ], + "x": [ + "ContainerRegistryMap", + "ContainerRegistryMapUri", + "DefinitionRepository", + "ParameterTemplatePath", + "WorkflowBucketOwnerId", + "readmeMarkdown", + "readmePath", + "readmeUri" + ] + }, + "AWS::Omics::WorkflowVersion": { + "a": "accelerators definition_uri description engine main parameter_template storage_capacity storage_type tags version_name workflow_bucket_owner_id workflow_id", + "m": [ + "ParameterTemplate", + "Tags" + ], + "x": [ + "ContainerRegistryMap", + "ContainerRegistryMapUri", + "DefinitionRepository", + "ParameterTemplatePath", + "readmeMarkdown", + "readmePath", + "readmeUri" + ] + }, + "AWS::OpenSearch::DataSource": { + "a": "data_source_type description domain_name name" + }, + "AWS::OpenSearchServerless::AccessPolicy": { + "a": "description name policy type" + }, + "AWS::OpenSearchServerless::Collection": { + "a": "collection_group_name deletion_protection description encryption_config name standby_replicas tags type vector_options" + }, + "AWS::OpenSearchServerless::CollectionGroup": { + "a": "capacity_limits description generation name standby_replicas tags" + }, + "AWS::OpenSearchServerless::CollectionIndex": { + "a": "collection_index_id index_name index_schema" + }, + "AWS::OpenSearchServerless::LifecyclePolicy": { + "a": "description name policy type" + }, + "AWS::OpenSearchServerless::SecurityConfig": { + "a": "description iam_federation_options iam_identity_center_options name saml_options type" + }, + "AWS::OpenSearchServerless::SecurityPolicy": { + "a": "description name policy type" + }, + "AWS::OpenSearchServerless::VpcEndpoint": { + "a": "name security_group_ids subnet_ids vpc_id" + }, + "AWS::OpenSearchService::Application": { + "a": "app_configs data_sources endpoint iam_identity_center_options kms_key_arn name tags" + }, + "AWS::OpenSearchService::Domain": { + "a": "accepted_warnings access_policies advanced_options advanced_security_options aiml_options automated_snapshot_pause_options cluster_config cognito_options deployment_strategy_options domain_endpoint_options domain_name ebs_options encryption_at_rest_options engine_mode engine_version identity_center_options ip_address_type log_publishing_options node_to_node_encryption_options off_peak_window_options skip_shard_migration_wait snapshot_options software_update_options tags use_case vpc_options", + "j": [ + "AccessPolicies" + ], + "m": [ + "AdvancedOptions", + "DomainEndpoints", + "LogPublishingOptions" + ] + }, + "AWS::Organizations::Account": { + "a": "account_name email parent_ids role_name tags" + }, + "AWS::Organizations::Organization": { + "a": "feature_set" + }, + "AWS::Organizations::OrganizationalUnit": { + "a": "name parent_id tags" + }, + "AWS::Organizations::Policy": { + "a": "content description name tags target_ids type", + "j": [ + "Content" + ] + }, + "AWS::Organizations::ResourcePolicy": { + "a": "content tags", + "j": [ + "Content" + ] + }, + "AWS::Outposts::Outpost": { + "a": "availability_zone availability_zone_id description name site_id supported_hardware_type tags" + }, + "AWS::Outposts::Site": { + "a": "description name notes operating_address rack_physical_properties shipping_address tags" + }, + "AWS::PCAConnectorAD::Connector": { + "a": "certificate_authority_arn directory_id tags vpc_information", + "m": [ + "Tags" + ] + }, + "AWS::PCAConnectorAD::DirectoryRegistration": { + "a": "directory_id tags", + "m": [ + "Tags" + ] + }, + "AWS::PCAConnectorAD::ServicePrincipalName": { + "a": "connector_arn directory_registration_arn" + }, + "AWS::PCAConnectorAD::Template": { + "a": "connector_arn definition name reenroll_all_certificate_holders tags", + "m": [ + "Tags" + ] + }, + "AWS::PCAConnectorAD::TemplateGroupAccessControlEntry": { + "a": "access_rights group_display_name group_security_identifier template_arn" + }, + "AWS::PCAConnectorSCEP::Challenge": { + "a": "connector_arn tags", + "m": [ + "Tags" + ] + }, + "AWS::PCAConnectorSCEP::Connector": { + "a": "certificate_authority_arn mobile_device_management tags vpc_endpoint_id", + "m": [ + "Tags" + ] + }, + "AWS::PCS::Cluster": { + "a": "name networking scheduler size slurm_configuration tags", + "m": [ + "Tags" + ] + }, + "AWS::PCS::ComputeNodeGroup": { + "a": "ami_id cluster_id custom_launch_template iam_instance_profile_arn instance_configs launch_template_mode name node_lifecycle_actions purchase_option scaling_configuration security_group_ids slurm_configuration spot_options ssh_key_name subnet_ids tags", + "m": [ + "Tags" + ] + }, + "AWS::PCS::Queue": { + "a": "cluster_id compute_node_group_configurations name slurm_configuration tags", + "m": [ + "Tags" + ] + }, + "AWS::PI::PerfReports": { + "a": "end_time identifier service_type start_time tags" + }, + "AWS::Panorama::ApplicationInstance": { + "a": "application_instance_id_to_replace default_runtime_context_device description manifest_overrides_payload manifest_payload name runtime_role_arn tags" + }, + "AWS::Panorama::Package": { + "a": "package_name storage_location tags" + }, + "AWS::Panorama::PackageVersion": { + "a": "mark_latest owner_account package_id package_version patch_version updated_latest_patch_version" + }, + "AWS::PaymentCryptography::Alias": { + "a": "alias_name key_arn" + }, + "AWS::PaymentCryptography::Key": { + "a": "derive_key_usage enabled exportable key_attributes key_check_value_algorithm policy replication_regions tags", + "m": [ + "ReplicationStatus" + ] + }, + "AWS::Personalize::Campaign": { + "a": "campaign_config min_provisioned_tps name solution_version_arn tags", + "m": [ + "CampaignConfig.ItemExplorationConfig", + "CampaignConfig.RankingInfluence" + ] + }, + "AWS::Personalize::Dataset": { + "a": "dataset_group_arn dataset_import_job dataset_type name schema_arn tags" + }, + "AWS::Personalize::DatasetGroup": { + "a": "domain kms_key_arn name role_arn tags" + }, + "AWS::Personalize::EventTracker": { + "a": "dataset_group_arn name tags" + }, + "AWS::Personalize::Filter": { + "a": "dataset_group_arn filter_expression name tags" + }, + "AWS::Personalize::MetricAttribution": { + "a": "dataset_group_arn metrics metrics_output_config name" + }, + "AWS::Personalize::Recommender": { + "a": "dataset_group_arn name recipe_arn recommender_config tags", + "m": [ + "RecommenderConfig.ItemExplorationConfig", + "RecommenderConfig.TrainingDataConfig.ExcludedDatasetColumns" + ] + }, + "AWS::Personalize::Schema": { + "a": "domain name schema tags" + }, + "AWS::Personalize::Solution": { + "a": "dataset_group_arn event_type name perform_auto_ml perform_hpo recipe_arn solution_config tags", + "m": [ + "SolutionConfig.AlgorithmHyperParameters", + "SolutionConfig.FeatureTransformationParameters" + ] + }, + "AWS::Pinpoint::InAppTemplate": { + "a": "content custom_config layout tags template_description template_name", + "j": [ + "CustomConfig", + "Tags" + ] + }, + "AWS::Pipes::Pipe": { + "a": "description desired_state enrichment enrichment_parameters kms_key_identifier log_configuration name role_arn source source_parameters tags target target_parameters", + "m": [ + "EnrichmentParameters.HttpParameters.HeaderParameters", + "EnrichmentParameters.HttpParameters.QueryStringParameters", + "Tags", + "TargetParameters.BatchJobParameters.Parameters", + "TargetParameters.HttpParameters.HeaderParameters", + "TargetParameters.HttpParameters.QueryStringParameters" + ] + }, + "AWS::Polly::Lexicon": { + "a": "content name" + }, + "AWS::PricingPlanManager::Subscription": { + "a": "plan_family plan_tier resource_arns usage_level" + }, + "AWS::Proton::EnvironmentAccountConnection": { + "a": "codebuild_role_arn component_role_arn environment_account_id environment_name management_account_id role_arn tags" + }, + "AWS::Proton::EnvironmentTemplate": { + "a": "description display_name encryption_key name provisioning tags" + }, + "AWS::Proton::ServiceTemplate": { + "a": "description display_name encryption_key name pipeline_provisioning tags" + }, + "AWS::QBusiness::Application": { + "a": "attachments_configuration auto_subscription_configuration client_ids_for_oidc description display_name encryption_configuration iam_identity_provider_arn identity_center_instance_arn identity_type personalization_configuration q_apps_configuration quick_sight_configuration role_arn tags" + }, + "AWS::QBusiness::DataSource": { + "a": "application_id configuration description display_name document_enrichment_configuration index_id media_extraction_configuration role_arn sync_schedule tags vpc_configuration" + }, + "AWS::QBusiness::Index": { + "a": "application_id capacity_configuration description display_name document_attribute_configurations tags type" + }, + "AWS::QBusiness::Permission": { + "a": "actions application_id conditions principal statement_id" + }, + "AWS::QBusiness::Plugin": { + "a": "application_id auth_configuration custom_plugin_configuration display_name server_url state tags type" + }, + "AWS::QBusiness::Retriever": { + "a": "application_id configuration display_name role_arn tags type" + }, + "AWS::QBusiness::WebExperience": { + "a": "application_id browser_extension_configuration customization_configuration identity_provider_configuration origins role_arn sample_prompts_control_mode subtitle tags title welcome_message" + }, + "AWS::QLDB::Stream": { + "a": "exclusive_end_time inclusive_start_time kinesis_configuration ledger_name role_arn stream_name tags" + }, + "AWS::QuickSight::ActionConnector": { + "a": "action_connector_id authentication_config aws_account_id description name permissions tags type vpc_connection_arn" + }, + "AWS::QuickSight::Agent": { + "a": "action_connectors agent_id agent_lifecycle aws_account_id custom_prompt_input description icon_id name spaces starter_prompts tags welcome_message" + }, + "AWS::QuickSight::Analysis": { + "a": "analysis_id aws_account_id errors name parameters permissions source_entity tags theme_arn", + "x": [ + "Definition", + "Errors.ViolatedEntities", + "FolderArns", + "SourceEntity.SourceTemplate.TopicReferences", + "ValidationStrategy" + ] + }, + "AWS::QuickSight::Assignment": { + "a": "assignment_name assignment_status identities namespace policy_arn", + "m": [ + "Identities" + ] + }, + "AWS::QuickSight::Brand": { + "a": "brand_definition brand_id tags" + }, + "AWS::QuickSight::CustomPermissions": { + "a": "aws_account_id capabilities custom_permissions_name tags" + }, + "AWS::QuickSight::Customization": { + "a": "default_theme namespace tags" + }, + "AWS::QuickSight::DLPSetting": { + "a": "aws_account_id dlp_setting_id enabled name provider_config provider_outage_action provider_type tags" + }, + "AWS::QuickSight::Dashboard": { + "a": "aws_account_id dashboard_id dashboard_publish_options name parameters permissions source_entity tags theme_arn version_description", + "x": [ + "DashboardPublishOptions.DataPointDrillUpDownOption", + "DashboardPublishOptions.DataPointMenuLabelOption", + "DashboardPublishOptions.DataPointTooltipOption", + "DashboardPublishOptions.DataQAEnabledOption", + "DashboardPublishOptions.DataStoriesSharingOption", + "DashboardPublishOptions.ExecutiveSummaryOption", + "DashboardPublishOptions.ExportWithHiddenFieldsOption", + "DashboardPublishOptions.QuickSuiteActionsOption", + "DashboardPublishOptions.SheetLayoutElementMaximizationOption", + "DashboardPublishOptions.VisualAxisSortOption", + "DashboardPublishOptions.VisualMenuOption", + "DashboardPublishOptions.VisualPublishOptions", + "Definition", + "FolderArns", + "LinkEntities", + "LinkSharingConfiguration", + "SourceEntity.SourceTemplate.TopicReferences", + "ValidationStrategy", + "Version.Errors.ViolatedEntities" + ] + }, + "AWS::QuickSight::DataSet": { + "a": "aws_account_id column_groups column_level_permission_rules data_set_id data_set_usage_configuration field_folders import_mode ingestion_wait_policy logical_table_map name permissions physical_table_map row_level_permission_data_set tags", + "m": [ + "FieldFolders", + "LogicalTableMap", + "PhysicalTableMap" + ], + "x": [ + "DataPrepConfiguration", + "DataSetRefreshProperties", + "DatasetParameters", + "FolderArns", + "OutputColumns.Id", + "OutputColumns.SubType", + "PerformanceConfiguration", + "RowLevelPermissionDataSet.Status", + "RowLevelPermissionTagConfiguration", + "SemanticModelConfiguration", + "UseAs" + ] + }, + "AWS::QuickSight::DataSource": { + "a": "alternate_data_source_parameters aws_account_id credentials data_source_id data_source_parameters error_info folder_arns name permissions ssl_properties tags type vpc_connection_properties" + }, + "AWS::QuickSight::Flow": { + "a": "aws_account_id description flow_definition name permissions" + }, + "AWS::QuickSight::Folder": { + "a": "aws_account_id folder_id folder_type name parent_folder_arn permissions sharing_model tags" + }, + "AWS::QuickSight::Group": { + "a": "description group_name namespace" + }, + "AWS::QuickSight::KnowledgeBase": { + "a": "access_control_configuration aws_account_id data_source_arn description is_email_notification_opted_for_ingestion_failures knowledge_base_configuration knowledge_base_id media_extraction_configuration name permissions primary_owner_arn tags" + }, + "AWS::QuickSight::LimitsProfile": { + "a": "account_id description profile_name resource_limits", + "m": [ + "ResourceLimits" + ] + }, + "AWS::QuickSight::OAuthClientApplication": { + "a": "client_id client_secret data_source_type identity_provider_vpc_connection_properties name o_auth_authorization_endpoint_url o_auth_client_application_id o_auth_client_authentication_type o_auth_scopes o_auth_token_endpoint_url tags" + }, + "AWS::QuickSight::RefreshSchedule": { + "a": "aws_account_id data_set_id schedule" + }, + "AWS::QuickSight::Space": { + "a": "aws_account_id description name permissions resources space_id tags" + }, + "AWS::QuickSight::Template": { + "a": "aws_account_id name permissions source_entity tags template_id version_description", + "x": [ + "Definition", + "SourceEntity.SourceAnalysis.TopicReferences", + "ValidationStrategy", + "Version.Errors.ViolatedEntities" + ] + }, + "AWS::QuickSight::Theme": { + "a": "aws_account_id base_theme_id configuration name permissions tags theme_id version_description" + }, + "AWS::QuickSight::Topic": { + "a": "aws_account_id config_options custom_instructions data_sets description folder_arns name tags topic_id user_experience_version", + "m": [ + "DataSets.CalculatedFields.SemanticType.TypeParameters", + "DataSets.Columns.SemanticType.TypeParameters", + "DataSets.NamedEntities.Definition.Metric.AggregationFunctionParameters", + "DataSets.NamedEntities.SemanticEntityType.TypeParameters" + ] + }, + "AWS::QuickSight::TopicV2": { + "a": "aws_account_id custom_instructions data_set_relations data_sets description folder_arns name permissions tags topic_id" + }, + "AWS::QuickSight::VPCConnection": { + "a": "availability_status aws_account_id dns_resolvers name role_arn security_group_ids subnet_ids tags vpc_connection_id" + }, + "AWS::RAM::Permission": { + "a": "name policy_template resource_type tags", + "j": [ + "PolicyTemplate" + ] + }, + "AWS::RAM::PermissionAssociation": { + "a": "permission_arn replace resource_share_arn" + }, + "AWS::RAM::PrincipalAssociation": { + "a": "principal resource_share_arn" + }, + "AWS::RAM::ResourceAssociation": { + "a": "resource_arn resource_share_arn" + }, + "AWS::RAM::ResourceShare": { + "a": "allow_external_principals name permission_arns principals resource_arns resource_share_configuration sources tags" + }, + "AWS::RAM::SourceAssociation": { + "a": "resource_share_arn source_id" + }, + "AWS::RDS::ClusterSnapshot": { + "a": "db_cluster_identifier db_cluster_snapshot_identifier tags" + }, + "AWS::RDS::CustomDBEngineVersion": { + "a": "database_installation_files database_installation_files_s3_bucket_name database_installation_files_s3_prefix description engine engine_version image_id kms_key_id manifest source_custom_db_engine_version_identifier status tags use_aws_provided_latest_image" + }, + "AWS::RDS::DBCluster": { + "a": "allocated_storage associated_roles auto_minor_version_upgrade availability_zones backtrack_window backup_retention_period cluster_scalability_type copy_tags_to_snapshot database_insights_mode database_name db_cluster_identifier db_cluster_instance_class db_cluster_parameter_group_name db_instance_parameter_group_name db_subnet_group_name db_system_id delete_automated_backups deletion_protection domain domain_iam_role_name enable_cloudwatch_logs_exports enable_global_write_forwarding enable_http_endpoint enable_iam_database_authentication enable_local_write_forwarding engine engine_lifecycle_support engine_mode engine_version global_cluster_identifier iops kms_key_id manage_master_user_password master_user_authentication_type master_user_password master_user_secret master_username monitoring_interval monitoring_role_arn network_type performance_insights_enabled performance_insights_kms_key_id performance_insights_retention_period port preferred_backup_window preferred_maintenance_window publicly_accessible replication_source_identifier restore_to_time restore_type scaling_configuration serverless_v2_scaling_configuration snapshot_identifier source_db_cluster_identifier source_db_cluster_resource_id source_region storage_encrypted storage_type tags use_latest_restorable_time vpc_security_group_ids with_express_configuration" + }, + "AWS::RDS::DBClusterEndpoint": { + "a": "custom_endpoint_type db_cluster_endpoint_identifier db_cluster_identifier excluded_members static_members tags" + }, + "AWS::RDS::DBClusterParameterGroup": { + "a": "db_cluster_parameter_group_name description family parameters tags", + "j": [ + "Parameters" + ] + }, + "AWS::RDS::DBInstance": { + "a": "additional_storage_volumes allocated_storage allow_major_version_upgrade apply_immediately associated_roles auto_minor_version_upgrade automatic_backup_replication_kms_key_id automatic_backup_replication_region automatic_backup_replication_retention_period availability_zone backup_retention_period backup_target ca_certificate_identifier certificate_rotation_restart character_set_name copy_tags_to_snapshot custom_iam_instance_profile database_insights_mode db_cluster_identifier db_cluster_snapshot_identifier db_instance_class db_instance_identifier db_name db_parameter_group_name db_security_groups db_snapshot_identifier db_subnet_group_name db_system_id dedicated_log_volume delete_automated_backups deletion_protection domain domain_auth_secret_arn domain_dns_ips domain_fqdn domain_iam_role_name domain_ou enable_cloudwatch_logs_exports enable_iam_database_authentication enable_performance_insights engine engine_lifecycle_support engine_version iops kms_key_id license_model manage_master_user_password master_user_authentication_type master_user_password master_user_secret master_username max_allocated_storage monitoring_interval monitoring_role_arn multi_az nchar_character_set_name network_type option_group_name performance_insights_kms_key_id performance_insights_retention_period port preferred_backup_window preferred_maintenance_window processor_features promotion_tier publicly_accessible replica_mode restore_time source_db_cluster_identifier source_db_instance_automated_backups_arn source_db_instance_identifier source_dbi_resource_id source_region storage_encrypted storage_throughput storage_type tags tde_credential_arn tde_credential_password timezone use_default_processor_features use_latest_restorable_time vpc_security_groups" + }, + "AWS::RDS::DBParameterGroup": { + "a": "db_parameter_group_name description family parameters tags", + "j": [ + "Parameters" + ] + }, + "AWS::RDS::DBProxy": { + "a": "auth db_proxy_name debug_logging default_auth_scheme endpoint_network_type engine_family idle_client_timeout require_tls role_arn tags target_connection_network_type vpc_security_group_ids vpc_subnet_ids" + }, + "AWS::RDS::DBProxyEndpoint": { + "a": "db_proxy_endpoint_name db_proxy_name endpoint_network_type tags target_role vpc_security_group_ids vpc_subnet_ids" + }, + "AWS::RDS::DBProxyTargetGroup": { + "a": "connection_pool_configuration_info db_cluster_identifiers db_instance_identifiers db_proxy_name tags target_group_name" + }, + "AWS::RDS::DBShardGroup": { + "a": "compute_redundancy db_cluster_identifier db_shard_group_identifier max_acu min_acu publicly_accessible tags" + }, + "AWS::RDS::DBSnapshot": { + "a": "db_instance_identifier db_snapshot_identifier tags" + }, + "AWS::RDS::DBSubnetGroup": { + "a": "db_subnet_group_description db_subnet_group_name subnet_ids tags" + }, + "AWS::RDS::Deployment": { + "a": "blue_green_deployment_name source tags target_allocated_storage target_db_cluster_parameter_group_name target_db_instance_class target_db_parameter_group_name target_engine_version target_iops target_storage_throughput target_storage_type upgrade_target_storage_config" + }, + "AWS::RDS::EventSubscription": { + "a": "enabled event_categories sns_topic_arn source_ids source_type subscription_name tags" + }, + "AWS::RDS::GlobalCluster": { + "a": "deletion_protection engine engine_lifecycle_support engine_version global_cluster_identifier source_db_cluster_identifier storage_encrypted tags", + "j": [ + "SourceDBClusterIdentifier" + ] + }, + "AWS::RDS::Integration": { + "a": "additional_encryption_context data_filter description integration_name kms_key_id source_arn tags target_arn", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::RDS::OptionGroup": { + "a": "engine_name major_engine_version option_configurations option_group_description option_group_name tags" + }, + "AWS::RTBFabric::InboundExternalLink": { + "a": "gateway_id link_attributes link_log_settings tags" + }, + "AWS::RTBFabric::Link": { + "a": "gateway_id http_responder_allowed link_attributes link_log_settings module_configuration_list peer_gateway_id tags" + }, + "AWS::RTBFabric::LinkRoutingRule": { + "a": "conditions gateway_id link_id priority tags" + }, + "AWS::RTBFabric::OutboundExternalLink": { + "a": "gateway_id link_attributes link_log_settings public_endpoint tags" + }, + "AWS::RTBFabric::RequesterGateway": { + "a": "description security_group_ids subnet_ids tags vpc_id" + }, + "AWS::RTBFabric::ResponderGateway": { + "a": "acm_certificate_arn description domain_name gateway_type listener_config managed_endpoint_configuration port protocol security_group_ids subnet_ids tags trust_store_configuration vpc_id" + }, + "AWS::RUM::AppMonitor": { + "a": "app_monitor_configuration custom_events cw_log_enabled deobfuscation_configuration domain domain_list name platform resource_policy tags", + "m": [ + "AppMonitorConfiguration.MetricDestinations.MetricDefinitions.DimensionKeys" + ] + }, + "AWS::Rbin::Rule": { + "a": "description exclude_resource_tags lock_configuration resource_tags resource_type retention_period status tags" + }, + "AWS::Redshift::Cluster": { + "a": "allow_version_upgrade aqua_configuration_status automated_snapshot_retention_period availability_zone availability_zone_relocation availability_zone_relocation_status classic cluster_identifier cluster_parameter_group_name cluster_security_groups cluster_subnet_group_name cluster_type cluster_version db_name defer_maintenance defer_maintenance_duration defer_maintenance_end_time defer_maintenance_start_time destination_region elastic_ip encrypted endpoint enhanced_vpc_routing hsm_client_certificate_identifier hsm_configuration_identifier iam_roles kms_key_id logging_properties maintenance_track_name manage_master_password manual_snapshot_retention_period master_password_secret_kms_key_id master_user_password master_username multi_az namespace_resource_policy node_type number_of_nodes owner_account port preferred_maintenance_window publicly_accessible resource_action revision_target rotate_encryption_key snapshot_cluster_identifier snapshot_copy_grant_name snapshot_copy_manual snapshot_copy_retention_period snapshot_identifier tags vpc_security_group_ids", + "j": [ + "KmsKeyId", + "MasterPasswordSecretKmsKeyId", + "NamespaceResourcePolicy" + ] + }, + "AWS::Redshift::ClusterParameterGroup": { + "a": "description parameter_group_family parameter_group_name parameters tags" + }, + "AWS::Redshift::ClusterSubnetGroup": { + "a": "description subnet_ids tags" + }, + "AWS::Redshift::EndpointAccess": { + "a": "cluster_identifier endpoint_name resource_owner subnet_group_name vpc_security_group_ids" + }, + "AWS::Redshift::EndpointAuthorization": { + "a": "account cluster_identifier force vpc_ids" + }, + "AWS::Redshift::EventSubscription": { + "a": "enabled event_categories severity sns_topic_arn source_ids source_type subscription_name tags" + }, + "AWS::Redshift::Integration": { + "a": "additional_encryption_context integration_name kms_key_id source_arn tags target_arn", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::Redshift::QEV2IdcApplication": { + "a": "idc_display_name idc_instance_arn qev_2_idc_application_name tags", + "n": "awscc_redshift_qev2_idc_application" + }, + "AWS::Redshift::RedshiftIdcApplication": { + "a": "application_type authorized_token_issuer_list iam_role_arn idc_display_name idc_instance_arn identity_namespace redshift_idc_application_name service_integrations sso_tag_keys tags" + }, + "AWS::Redshift::ScheduledAction": { + "a": "enable end_time iam_role schedule scheduled_action_description scheduled_action_name start_time target_action" + }, + "AWS::Redshift::Snapshot": { + "a": "cluster_identifier manual_snapshot_retention_period snapshot_identifier tags" + }, + "AWS::Redshift::SnapshotCopyGrant": { + "a": "kms_key_id snapshot_copy_grant_name tags" + }, + "AWS::Redshift::SnapshotSchedule": { + "a": "schedule_definitions schedule_description schedule_identifier tags" + }, + "AWS::Redshift::UsageLimit": { + "a": "amount breach_action cluster_identifier feature_type limit_type period tags" + }, + "AWS::RedshiftServerless::Namespace": { + "a": "admin_password_secret_kms_key_id admin_user_password admin_username db_name default_iam_role_arn final_snapshot_name final_snapshot_retention_period iam_roles kms_key_id log_exports manage_admin_password namespace_name namespace_resource_policy redshift_idc_application_arn snapshot_copy_configurations tags", + "j": [ + "NamespaceResourcePolicy" + ] + }, + "AWS::RedshiftServerless::Snapshot": { + "a": "namespace_name retention_period snapshot_name tags" + }, + "AWS::RedshiftServerless::Workgroup": { + "a": "base_capacity config_parameters enhanced_vpc_routing max_capacity namespace_name port price_performance_target publicly_accessible recovery_point_id security_group_ids snapshot_arn snapshot_name snapshot_owner_account subnet_ids tags track_name workgroup workgroup_name" + }, + "AWS::RefactorSpaces::Application": { + "a": "api_gateway_proxy environment_identifier name proxy_type tags vpc_id" + }, + "AWS::RefactorSpaces::Environment": { + "a": "description name network_fabric_type tags" + }, + "AWS::RefactorSpaces::Route": { + "a": "application_identifier default_route environment_identifier route_type service_identifier tags uri_path_route" + }, + "AWS::RefactorSpaces::Service": { + "a": "application_identifier description endpoint_type environment_identifier lambda_endpoint name tags url_endpoint vpc_id" + }, + "AWS::Rekognition::Collection": { + "a": "collection_id tags" + }, + "AWS::Rekognition::Dataset": { + "a": "dataset_type project_arn tags" + }, + "AWS::Rekognition::Project": { + "a": "project_name tags" + }, + "AWS::ResilienceHub::App": { + "a": "app_assessment_schedule app_template_body description event_subscriptions name permission_model resiliency_policy_arn resource_mappings tags", + "m": [ + "Tags" + ] + }, + "AWS::ResilienceHub::ResiliencyPolicy": { + "a": "data_location_constraint policy policy_description policy_name tags tier", + "m": [ + "Tags" + ] + }, + "AWS::ResilienceHubV2::Policy": { + "a": "availability_slo data_recovery description kms_key_id multi_az multi_region name sharing_enabled tags" + }, + "AWS::ResilienceHubV2::Service": { + "a": "assertions associated_systems dependency_discovery description dev_ops_agent_configuration input_sources kms_key_id name permission_model policy_arn regions report_configuration tags", + "m": [ + "InputSources.ResourceConfiguration.Eks.LabelSelector.MatchLabels" + ] + }, + "AWS::ResilienceHubV2::ServiceFunction": { + "a": "criticality description name service_arn" + }, + "AWS::ResilienceHubV2::System": { + "a": "description kms_key_id name sharing_enabled tags" + }, + "AWS::ResilienceHubV2::UserJourney": { + "a": "description name policy_arn system_identifier" + }, + "AWS::ResourceExplorer2::DefaultViewAssociation": { + "a": "view_arn" + }, + "AWS::ResourceExplorer2::Index": { + "a": "tags type", + "m": [ + "Tags" + ] + }, + "AWS::ResourceExplorer2::View": { + "a": "filters included_properties scope tags view_name", + "m": [ + "Tags" + ] + }, + "AWS::ResourceGroups::Group": { + "a": "configuration description name resource_query resources tags" + }, + "AWS::ResourceGroups::TagSyncTask": { + "a": "group role_arn tag_key tag_value" + }, + "AWS::RoboMaker::Fleet": { + "a": "name tags", + "m": [ + "Tags" + ] + }, + "AWS::RoboMaker::Robot": { + "a": "architecture fleet greengrass_group_id name tags", + "m": [ + "Tags" + ] + }, + "AWS::RoboMaker::RobotApplication": { + "a": "current_revision_id environment name robot_software_suite sources tags", + "m": [ + "Tags" + ] + }, + "AWS::RoboMaker::RobotApplicationVersion": { + "a": "application current_revision_id" + }, + "AWS::RoboMaker::SimulationApplication": { + "a": "current_revision_id environment name rendering_engine robot_software_suite simulation_software_suite sources tags", + "m": [ + "Tags" + ] + }, + "AWS::RoboMaker::SimulationApplicationVersion": { + "a": "application current_revision_id" + }, + "AWS::RolesAnywhere::CRL": { + "a": "crl_data enabled name tags trust_anchor_arn" + }, + "AWS::RolesAnywhere::Profile": { + "a": "accept_role_session_name attribute_mappings duration_seconds enabled managed_policy_arns name require_instance_properties role_arns session_policy tags" + }, + "AWS::RolesAnywhere::TrustAnchor": { + "a": "enabled name notification_settings source tags", + "x": [ + "CrlDpRevocationEnabled" + ] + }, + "AWS::Route53::CidrCollection": { + "a": "locations name" + }, + "AWS::Route53::DNSSEC": { + "a": "hosted_zone_id" + }, + "AWS::Route53::DelegationSet": {}, + "AWS::Route53::HealthCheck": { + "a": "health_check_config health_check_tags", + "x": [ + "HealthCheckConfig.EndpointType", + "HealthCheckConfig.HealthCheckSourceId" + ] + }, + "AWS::Route53::HostedZone": { + "a": "delegation_set_id hosted_zone_config hosted_zone_features hosted_zone_tags name query_logging_config vp_cs", + "x": [ + "HostedZoneConfig.HostedZoneTier", + "HostedZoneFeatures.ChangeGuardrails", + "HostedZoneFeatures.ChangeHistory", + "HostedZoneFeatures.EnablePublicDNSFallback" + ] + }, + "AWS::Route53::KeySigningKey": { + "a": "hosted_zone_id key_management_service_arn name status" + }, + "AWS::Route53::QueryLoggingConfig": { + "a": "cloudwatch_logs_log_group_arn hosted_zone_id" + }, + "AWS::Route53::RecordSet": { + "a": "alias_target cidr_routing_config comment failover geo_location health_check_id hosted_zone_id hosted_zone_name multi_value_answer name region resource_records set_identifier ttl type weight", + "x": [ + "AZAffinity" + ] + }, + "AWS::Route53::TrafficPolicy": { + "a": "comment document name" + }, + "AWS::Route53::TrafficPolicyInstance": { + "a": "hosted_zone_id name traffic_policy_id traffic_policy_version ttl" + }, + "AWS::Route53GlobalResolver::AccessSource": { + "a": "cidr client_token dns_view_id ip_address_type name protocol tags", + "x": [ + "CoreNetworkEndpointId", + "Segment" + ] + }, + "AWS::Route53GlobalResolver::AccessToken": { + "a": "client_token dns_view_id expires_at name tags" + }, + "AWS::Route53GlobalResolver::DnsView": { + "a": "client_token description dnssec_validation edns_client_subnet firewall_rules_fail_open global_resolver_id name tags" + }, + "AWS::Route53GlobalResolver::FirewallDomainList": { + "a": "client_token description domain_file_url domains global_resolver_id name tags" + }, + "AWS::Route53GlobalResolver::FirewallRule": { + "a": "action block_override_dns_type block_override_domain block_override_ttl block_response client_token confidence_threshold description dns_advanced_protection dns_view_id firewall_domain_list_id name priority q_type" + }, + "AWS::Route53GlobalResolver::GlobalResolver": { + "a": "client_token description ip_address_type name observability_region regions tags", + "x": [ + "PublicIpStatus" + ] + }, + "AWS::Route53GlobalResolver::HostedZoneAssociation": { + "a": "hosted_zone_id name resource_arn" + }, + "AWS::Route53Profiles::Profile": { + "a": "name tags" + }, + "AWS::Route53Profiles::ProfileAssociation": { + "a": "arn name priority profile_id resource_id tags" + }, + "AWS::Route53Profiles::ProfileResourceAssociation": { + "a": "name profile_id resource_arn resource_properties" + }, + "AWS::Route53RecoveryControl::Cluster": { + "a": "name network_type tags" + }, + "AWS::Route53RecoveryControl::ControlPanel": { + "a": "cluster_arn name tags" + }, + "AWS::Route53RecoveryControl::RoutingControl": { + "a": "cluster_arn control_panel_arn name" + }, + "AWS::Route53RecoveryControl::SafetyRule": { + "a": "assertion_rule control_panel_arn gating_rule name rule_config tags" + }, + "AWS::Route53RecoveryReadiness::Cell": { + "a": "cell_name cells tags" + }, + "AWS::Route53RecoveryReadiness::ReadinessCheck": { + "a": "readiness_check_name resource_set_name tags" + }, + "AWS::Route53RecoveryReadiness::RecoveryGroup": { + "a": "cells recovery_group_name tags" + }, + "AWS::Route53RecoveryReadiness::ResourceSet": { + "a": "resource_set_name resource_set_type resources tags", + "r": { + "Resources.DnsTargetResource.TargetResource.R53Resource": "r53_resource" + } + }, + "AWS::Route53Resolver::FirewallConfig": { + "a": "firewall_fail_open resource_id" + }, + "AWS::Route53Resolver::FirewallDomainList": { + "a": "domain_file_url domains name tags" + }, + "AWS::Route53Resolver::FirewallRuleGroup": { + "a": "firewall_rules name tags" + }, + "AWS::Route53Resolver::FirewallRuleGroupAssociation": { + "a": "firewall_rule_group_id mutation_protection name priority tags vpc_id" + }, + "AWS::Route53Resolver::OutpostResolver": { + "a": "instance_count name outpost_arn preferred_instance_type tags" + }, + "AWS::Route53Resolver::ResolverConfig": { + "a": "autodefined_reverse_flag resource_id" + }, + "AWS::Route53Resolver::ResolverDNSSECConfig": { + "a": "resource_id" + }, + "AWS::Route53Resolver::ResolverEndpoint": { + "a": "direction dns_64_enabled ip_addresses ipv_6_internet_access_enabled name outpost_arn preferred_instance_type protocols resolver_endpoint_type rni_enhanced_metrics_enabled security_group_ids tags target_name_server_metrics_enabled" + }, + "AWS::Route53Resolver::ResolverQueryLoggingConfig": { + "a": "destination_arn name tags" + }, + "AWS::Route53Resolver::ResolverQueryLoggingConfigAssociation": { + "a": "resolver_query_log_config_id resource_id" + }, + "AWS::Route53Resolver::ResolverRule": { + "a": "delegation_record domain_name name resolver_endpoint_id rule_type tags target_ips" + }, + "AWS::Route53Resolver::ResolverRuleAssociation": { + "a": "name resolver_rule_id vpc_id" + }, + "AWS::S3::AccessGrant": { + "a": "access_grants_location_configuration access_grants_location_id application_arn grantee permission s3_prefix_type tags" + }, + "AWS::S3::AccessGrantsInstance": { + "a": "identity_center_arn tags" + }, + "AWS::S3::AccessGrantsLocation": { + "a": "iam_role_arn location_scope tags" + }, + "AWS::S3::AccessPoint": { + "a": "bucket bucket_account_id name policy public_access_block_configuration tags vpc_configuration", + "j": [ + "Policy" + ] + }, + "AWS::S3::Bucket": { + "a": "abac_status accelerate_configuration access_control analytics_configurations bucket_encryption bucket_name bucket_name_prefix bucket_namespace cors_configuration intelligent_tiering_configurations inventory_configurations lifecycle_configuration logging_configuration metadata_configuration metadata_table_configuration metrics_configurations notification_configuration object_lock_configuration object_lock_enabled ownership_controls public_access_block_configuration replication_configuration tags versioning_configuration website_configuration" + }, + "AWS::S3::BucketPolicy": { + "a": "bucket policy_document", + "j": [ + "PolicyDocument" + ] + }, + "AWS::S3::MultiRegionAccessPoint": { + "a": "name public_access_block_configuration regions" + }, + "AWS::S3::MultiRegionAccessPointPolicy": { + "a": "mrap_name policy", + "j": [ + "Policy" + ] + }, + "AWS::S3::StorageLens": { + "a": "storage_lens_configuration tags", + "x": [ + "StorageLensConfiguration.CostAndUsageReportsPublish", + "StorageLensConfiguration.IntAccessTiers" + ] + }, + "AWS::S3::StorageLensGroup": { + "a": "filter name tags" + }, + "AWS::S3Express::AccessPoint": { + "a": "bucket bucket_account_id name policy public_access_block_configuration scope tags vpc_configuration", + "j": [ + "Policy" + ] + }, + "AWS::S3Express::BucketPolicy": { + "a": "bucket policy_document", + "j": [ + "PolicyDocument" + ] + }, + "AWS::S3Express::DirectoryBucket": { + "a": "bucket_encryption bucket_name data_redundancy inventory_configurations lifecycle_configuration location_name metrics_configurations tags", + "j": [ + "BucketEncryption.ServerSideEncryptionConfiguration.ServerSideEncryptionByDefault.KMSMasterKeyID" + ] + }, + "AWS::S3Files::AccessPoint": { + "a": "client_token file_system_id posix_user root_directory tags" + }, + "AWS::S3Files::FileSystem": { + "a": "accept_bucket_warning bucket client_token kms_key_id prefix role_arn synchronization_configuration tags" + }, + "AWS::S3Files::FileSystemPolicy": { + "a": "file_system_id policy", + "j": [ + "Policy" + ] + }, + "AWS::S3Files::MountTarget": { + "a": "file_system_id ip_address_type ipv_4_address ipv_6_address security_groups subnet_id" + }, + "AWS::S3ObjectLambda::AccessPoint": { + "a": "name object_lambda_configuration" + }, + "AWS::S3ObjectLambda::AccessPointPolicy": { + "a": "object_lambda_access_point policy_document", + "j": [ + "PolicyDocument" + ] + }, + "AWS::S3Outposts::AccessPoint": { + "a": "bucket name policy vpc_configuration", + "j": [ + "Policy" + ] + }, + "AWS::S3Outposts::Bucket": { + "a": "bucket_name lifecycle_configuration outpost_id tags" + }, + "AWS::S3Outposts::BucketPolicy": { + "a": "bucket policy_document", + "j": [ + "PolicyDocument" + ] + }, + "AWS::S3Outposts::Endpoint": { + "a": "access_type customer_owned_ipv_4_pool failed_reason outpost_id security_group_id subnet_id" + }, + "AWS::S3Tables::Namespace": { + "a": "namespace table_bucket_arn" + }, + "AWS::S3Tables::Table": { + "a": "compaction iceberg_metadata namespace open_table_format snapshot_management storage_class_configuration table_bucket_arn table_name tags without_metadata", + "j": [ + "IcebergMetadata.IcebergSchemaV2.SchemaV2FieldList.Type" + ], + "m": [ + "IcebergMetadata.TableProperties" + ] + }, + "AWS::S3Tables::TableBucket": { + "a": "encryption_configuration metrics_configuration replication_configuration storage_class_configuration table_bucket_name tags unreferenced_file_removal", + "x": [ + "LoggingConfiguration" + ] + }, + "AWS::S3Tables::TableBucketPolicy": { + "a": "resource_policy table_bucket_arn", + "j": [ + "ResourcePolicy" + ] + }, + "AWS::S3Tables::TablePolicy": { + "a": "resource_policy table_arn", + "j": [ + "ResourcePolicy" + ] + }, + "AWS::S3Vectors::Index": { + "a": "data_type dimension distance_metric encryption_configuration index_name metadata_configuration tags vector_bucket_arn vector_bucket_name", + "x": [ + "MetadataConfiguration.TextSearchConfigurations" + ] + }, + "AWS::S3Vectors::VectorBucket": { + "a": "encryption_configuration tags vector_bucket_name" + }, + "AWS::S3Vectors::VectorBucketPolicy": { + "a": "policy vector_bucket_arn vector_bucket_name", + "j": [ + "Policy" + ] + }, + "AWS::SCN::DataIntegrationFlow": { + "a": "instance_id name sources tags target transformation" + }, + "AWS::SCN::Dataset": { + "a": "description instance_id name namespace partition_spec schema tags" + }, + "AWS::SCN::Instance": { + "a": "instance_description instance_name tags web_app_dns_domain" + }, + "AWS::SCN::Namespace": { + "a": "description instance_id name tags" + }, + "AWS::SDB::Domain": { + "a": "description" + }, + "AWS::SES::ConfigurationSet": { + "a": "archiving_options delivery_options name reputation_options sending_options suppression_options tags tracking_options vdm_options" + }, + "AWS::SES::ConfigurationSetEventDestination": { + "a": "configuration_set_name event_destination" + }, + "AWS::SES::ContactList": { + "a": "contact_list_name description tags topics" + }, + "AWS::SES::CustomVerificationEmailTemplate": { + "a": "failure_redirection_url from_email_address success_redirection_url tags template_content template_name template_subject" + }, + "AWS::SES::DedicatedIpPool": { + "a": "pool_name scaling_mode tags" + }, + "AWS::SES::EmailIdentity": { + "a": "configuration_set_attributes dkim_attributes dkim_signing_attributes email_identity feedback_attributes mail_from_attributes tags" + }, + "AWS::SES::EmailIdentityCertificate": { + "a": "certificate_arn email_identity from_address" + }, + "AWS::SES::MailManagerAddonInstance": { + "a": "addon_subscription_id tags" + }, + "AWS::SES::MailManagerAddonSubscription": { + "a": "addon_name tags" + }, + "AWS::SES::MailManagerAddressList": { + "a": "address_list_name tags" + }, + "AWS::SES::MailManagerArchive": { + "a": "archive_name kms_key_arn retention tags" + }, + "AWS::SES::MailManagerIngressPoint": { + "a": "ingress_point_configuration ingress_point_name network_configuration rule_set_id status_to_update tags tls_policy traffic_policy_id type" + }, + "AWS::SES::MailManagerRelay": { + "a": "authentication relay_name server_name server_port tags" + }, + "AWS::SES::MailManagerRuleSet": { + "a": "rule_set_name rules tags" + }, + "AWS::SES::MailManagerTrafficPolicy": { + "a": "default_action max_message_size_bytes policy_statements tags traffic_policy_name" + }, + "AWS::SES::MultiRegionEndpoint": { + "a": "details endpoint_name tags" + }, + "AWS::SES::ReceiptFilter": { + "a": "filter" + }, + "AWS::SES::ReceiptRuleSet": { + "a": "rule_set_name" + }, + "AWS::SES::Template": { + "a": "tags template" + }, + "AWS::SES::Tenant": { + "a": "reputation_entity resource_associations suppression_attributes tags tenant_name" + }, + "AWS::SES::VdmAttributes": { + "a": "dashboard_attributes guardian_attributes" + }, + "AWS::SMSVOICE::ConfigurationSet": { + "a": "configuration_set_name default_sender_id event_destinations message_feedback_enabled protect_configuration_id tags" + }, + "AWS::SMSVOICE::NotifyConfiguration": { + "a": "default_template_id deletion_protection_enabled display_name enabled_channels enabled_countries pool_id tags use_case" + }, + "AWS::SMSVOICE::OptOutList": { + "a": "opt_out_list_name tags" + }, + "AWS::SMSVOICE::PhoneNumber": { + "a": "deletion_protection_enabled iso_country_code mandatory_keywords number_capabilities number_type opt_out_list_name optional_keywords self_managed_opt_outs_enabled tags two_way" + }, + "AWS::SMSVOICE::Pool": { + "a": "deletion_protection_enabled mandatory_keywords opt_out_list_name optional_keywords origination_identities self_managed_opt_outs_enabled shared_routes_enabled tags two_way" + }, + "AWS::SMSVOICE::ProtectConfiguration": { + "a": "country_rule_set deletion_protection_enabled tags" + }, + "AWS::SMSVOICE::RcsAgent": { + "a": "deletion_protection_enabled opt_out_list_name self_managed_opt_outs_enabled tags two_way_channel_arn two_way_channel_role two_way_enabled two_way_media_s3_bucket_name two_way_media_s3_key_prefix two_way_media_s3_role two_way_rcs_events_enabled" + }, + "AWS::SMSVOICE::Registration": { + "a": "registration_type tags" + }, + "AWS::SMSVOICE::RegistrationAttachment": { + "a": "attachment_body attachment_url tags" + }, + "AWS::SMSVOICE::ResourcePolicy": { + "a": "policy_document resource_arn", + "j": [ + "PolicyDocument" + ] + }, + "AWS::SMSVOICE::SenderId": { + "a": "deletion_protection_enabled iso_country_code sender_id tags" + }, + "AWS::SMSVOICE::VerifiedDestinationNumber": { + "a": "destination_phone_number tags" + }, + "AWS::SNS::Subscription": { + "a": "delivery_policy endpoint filter_policy filter_policy_scope protocol raw_message_delivery redrive_policy region replay_policy subscription_role_arn topic_arn", + "j": [ + "DeliveryPolicy", + "FilterPolicy", + "RedrivePolicy", + "ReplayPolicy" + ] + }, + "AWS::SNS::Topic": { + "a": "archive_policy content_based_deduplication data_protection_policy delivery_status_logging display_name fifo_throughput_scope fifo_topic kms_master_key_id maximum_message_size signature_version subscription tags topic_name tracing_config", + "j": [ + "ArchivePolicy", + "DataProtectionPolicy" + ] + }, + "AWS::SNS::TopicInlinePolicy": { + "a": "policy_document topic_arn", + "j": [ + "PolicyDocument" + ] + }, + "AWS::SQS::Queue": { + "a": "content_based_deduplication deduplication_scope delay_seconds fifo_queue fifo_throughput_limit kms_data_key_reuse_period_seconds kms_master_key_id maximum_message_size message_retention_period queue_name receive_message_wait_time_seconds redrive_allow_policy redrive_policy sqs_managed_sse_enabled tags visibility_timeout", + "j": [ + "RedriveAllowPolicy", + "RedrivePolicy" + ] + }, + "AWS::SQS::QueueInlinePolicy": { + "a": "policy_document queue", + "j": [ + "PolicyDocument" + ] + }, + "AWS::SSM::Association": { + "a": "apply_only_at_cron_interval association_dispatch_assume_role association_name automation_target_parameter_name calendar_names compliance_severity document_version instance_id max_concurrency max_errors name output_location parameters schedule_expression schedule_offset sync_compliance tags targets wait_for_success_timeout_seconds", + "m": [ + "Parameters" + ] + }, + "AWS::SSM::CloudConnector": { + "a": "config_connector_arn configuration description display_name role_arn tags", + "x": [ + "Configuration.GcpConfiguration" + ] + }, + "AWS::SSM::Document": { + "a": "attachments content document_format document_type name requires tags target_type update_method version_name", + "j": [ + "Content" + ] + }, + "AWS::SSM::MaintenanceWindow": { + "a": "allow_unassociated_targets cutoff description duration end_date name schedule schedule_offset schedule_timezone start_date tags" + }, + "AWS::SSM::MaintenanceWindowTarget": { + "a": "description name owner_information resource_type targets window_id" + }, + "AWS::SSM::MaintenanceWindowTask": { + "a": "cutoff_behavior description logging_info max_concurrency max_errors name priority service_role_arn targets task_arn task_invocation_parameters task_parameters task_type window_id", + "j": [ + "TaskInvocationParameters.MaintenanceWindowAutomationParameters.Parameters", + "TaskInvocationParameters.MaintenanceWindowRunCommandParameters.Parameters", + "TaskParameters" + ] + }, + "AWS::SSM::OpsItem": { + "a": "category description priority severity source tags title" + }, + "AWS::SSM::Parameter": { + "a": "allowed_pattern data_type description name policies tags tier type value", + "m": [ + "Tags" + ] + }, + "AWS::SSM::PatchBaseline": { + "a": "approval_rules approved_patches approved_patches_compliance_level approved_patches_enable_non_security available_security_updates_compliance_status default_baseline description global_filters name operating_system patch_groups rejected_patches rejected_patches_action sources tags" + }, + "AWS::SSM::ResourceDataSync": { + "a": "bucket_name bucket_prefix bucket_region kms_key_arn s3_destination sync_format sync_name sync_source sync_type" + }, + "AWS::SSM::ResourcePolicy": { + "a": "policy resource_arn", + "j": [ + "Policy" + ] + }, + "AWS::SSM::ServiceSetting": { + "a": "setting_id setting_value" + }, + "AWS::SSMContacts::Contact": { + "a": "alias display_name plan tags type" + }, + "AWS::SSMContacts::ContactChannel": { + "a": "channel_address channel_name channel_type contact_id defer_activation" + }, + "AWS::SSMContacts::Plan": { + "a": "contact_id rotation_ids stages" + }, + "AWS::SSMContacts::Rotation": { + "a": "contact_ids name recurrence start_time tags time_zone_id" + }, + "AWS::SSMGuiConnect::Preferences": { + "a": "connection_recording_preferences" + }, + "AWS::SSMIncidents::ReplicationSet": { + "a": "deletion_protected regions tags" + }, + "AWS::SSMIncidents::ResponsePlan": { + "a": "actions chat_channel display_name engagements incident_template integrations name tags" + }, + "AWS::SSMQuickSetup::ConfigurationManager": { + "a": "configuration_definitions description name tags", + "m": [ + "ConfigurationDefinitions.Parameters", + "StatusSummaries.StatusDetails", + "Tags" + ] + }, + "AWS::SSMQuickSetup::LifecycleAutomation": { + "a": "automation_document automation_parameters resource_key tags", + "m": [ + "AutomationParameters", + "Tags" + ] + }, + "AWS::SSO::Application": { + "a": "application_provider_arn description instance_arn name portal_options status tags" + }, + "AWS::SSO::ApplicationAssignment": { + "a": "application_arn principal_id principal_type" + }, + "AWS::SSO::Assignment": { + "a": "instance_arn permission_set_arn principal_id principal_type target_id target_type" + }, + "AWS::SSO::Instance": { + "a": "name tags" + }, + "AWS::SSO::InstanceAccessControlAttributeConfiguration": { + "a": "access_control_attributes instance_access_control_attribute_configuration instance_arn" + }, + "AWS::SSO::PermissionSet": { + "a": "customer_managed_policy_references description inline_policy instance_arn managed_policies name permissions_boundary relay_state_type session_duration tags", + "j": [ + "InlinePolicy" + ] + }, + "AWS::SageMaker::AIWorkloadConfig": { + "a": "ai_workload_config_name ai_workload_configs dataset_config tags" + }, + "AWS::SageMaker::Action": { + "a": "action_name action_type description metadata_properties properties source status tags", + "m": [ + "Properties" + ] + }, + "AWS::SageMaker::Algorithm": { + "a": "algorithm_description algorithm_name certify_for_marketplace inference_specification tags training_specification", + "m": [ + "InferenceSpecification.Containers.Environment" + ] + }, + "AWS::SageMaker::App": { + "a": "app_name app_type domain_id recovery_mode resource_spec tags user_profile_name" + }, + "AWS::SageMaker::AppImageConfig": { + "a": "app_image_config_name code_editor_app_image_config jupyter_lab_app_image_config kernel_gateway_image_config tags" + }, + "AWS::SageMaker::Artifact": { + "a": "artifact_name artifact_type metadata_properties properties source tags", + "m": [ + "Properties" + ] + }, + "AWS::SageMaker::Cluster": { + "a": "auto_scaling cluster_name cluster_role instance_groups node_provisioning_mode node_recovery orchestrator restricted_instance_groups restricted_instance_groups_config tags tiered_storage_config vpc_config", + "j": [ + "InstanceGroups.CapacityRequirements.OnDemand", + "InstanceGroups.CapacityRequirements.Spot" + ], + "m": [ + "InstanceGroups.KubernetesConfig.Labels" + ] + }, + "AWS::SageMaker::ClusterSchedulerConfig": { + "a": "cluster_arn description name scheduler_config tags" + }, + "AWS::SageMaker::CodeRepository": { + "a": "code_repository_name git_config tags" + }, + "AWS::SageMaker::ComputeQuota": { + "a": "activation_state cluster_arn compute_quota_config compute_quota_target description name tags" + }, + "AWS::SageMaker::Context": { + "a": "context_name context_type description properties source tags", + "m": [ + "Properties" + ] + }, + "AWS::SageMaker::DataQualityJobDefinition": { + "a": "data_quality_app_specification data_quality_baseline_config data_quality_job_input data_quality_job_output_config endpoint_name job_definition_name job_resources network_config role_arn stopping_condition tags", + "m": [ + "DataQualityAppSpecification.Environment" + ] + }, + "AWS::SageMaker::Device": { + "a": "device device_fleet_name tags" + }, + "AWS::SageMaker::DeviceFleet": { + "a": "description device_fleet_name output_config role_arn tags" + }, + "AWS::SageMaker::Domain": { + "a": "app_network_access_type app_security_group_management auth_mode default_space_settings default_user_settings domain_name domain_settings home_efs_file_system_creation kms_key_id subnet_ids tag_propagation tags vpc_id" + }, + "AWS::SageMaker::Endpoint": { + "a": "deployment_config endpoint_config_name endpoint_name exclude_retained_variant_properties retain_all_variant_properties retain_deployment_config tags" + }, + "AWS::SageMaker::EndpointConfig": { + "a": "async_inference_config data_capture_config enable_network_isolation endpoint_config_name execution_role_arn explainer_config kms_key_id metrics_config production_variants shadow_production_variants tags vpc_config", + "x": [ + "CrossRegionTrafficConfig" + ] + }, + "AWS::SageMaker::Experiment": { + "a": "description display_name experiment_name tags" + }, + "AWS::SageMaker::ExperimentTrialComponent": { + "a": "display_name end_time metadata_properties start_time status tags trial_component_name" + }, + "AWS::SageMaker::FeatureGroup": { + "a": "description event_time_feature_name feature_definitions feature_group_name offline_store_config online_store_config record_identifier_feature_name role_arn tags throughput_config" + }, + "AWS::SageMaker::Hub": { + "a": "hub_description hub_display_name hub_name hub_search_keywords s3_storage_config tags" + }, + "AWS::SageMaker::HumanTaskUi": { + "a": "human_task_ui_name tags ui_template" + }, + "AWS::SageMaker::Image": { + "a": "image_description image_display_name image_name image_role_arn tags" + }, + "AWS::SageMaker::ImageVersion": { + "a": "alias aliases base_image horovod image_name job_type ml_framework processor programming_lang release_notes vendor_guidance" + }, + "AWS::SageMaker::InferenceComponent": { + "a": "deployment_config endpoint_arn endpoint_name inference_component_name runtime_config specification specifications tags variant_name", + "m": [ + "Specification.Container.Environment", + "Specifications.Container.Environment" + ] + }, + "AWS::SageMaker::InferenceExperiment": { + "a": "data_storage_config description desired_state endpoint_name kms_key model_variants name role_arn schedule shadow_mode_config status_reason tags type" + }, + "AWS::SageMaker::MlflowApp": { + "a": "artifact_store_uri model_registration_mode name role_arn tags weekly_maintenance_window_start" + }, + "AWS::SageMaker::MlflowTrackingServer": { + "a": "artifact_store_uri automatic_model_registration mlflow_version role_arn tags tracking_server_name tracking_server_size weekly_maintenance_window_start" + }, + "AWS::SageMaker::Model": { + "a": "containers enable_network_isolation execution_role_arn inference_execution_config model_name primary_container tags vpc_config", + "j": [ + "Containers.Environment", + "PrimaryContainer.Environment" + ] + }, + "AWS::SageMaker::ModelBiasJobDefinition": { + "a": "endpoint_name job_definition_name job_resources model_bias_app_specification model_bias_baseline_config model_bias_job_input model_bias_job_output_config network_config role_arn stopping_condition tags", + "m": [ + "ModelBiasAppSpecification.Environment" + ] + }, + "AWS::SageMaker::ModelExplainabilityJobDefinition": { + "a": "endpoint_name job_definition_name job_resources model_explainability_app_specification model_explainability_baseline_config model_explainability_job_input model_explainability_job_output_config network_config role_arn stopping_condition tags", + "m": [ + "ModelExplainabilityAppSpecification.Environment" + ] + }, + "AWS::SageMaker::ModelPackage": { + "a": "additional_inference_specifications additional_inference_specifications_to_add approval_description certify_for_marketplace client_token customer_metadata_properties domain drift_check_baselines inference_specification metadata_properties model_approval_status model_card model_metrics model_package_description model_package_group_name model_package_name model_package_status_details model_package_version sample_payload_url security_config skip_model_validation source_algorithm_specification source_uri tags task validation_specification", + "m": [ + "AdditionalInferenceSpecifications.Containers.Environment", + "AdditionalInferenceSpecificationsToAdd.Containers.Environment", + "CustomerMetadataProperties", + "InferenceSpecification.Containers.Environment", + "ValidationSpecification.ValidationProfiles.TransformJobDefinition.Environment" + ] + }, + "AWS::SageMaker::ModelPackageGroup": { + "a": "model_package_group_description model_package_group_name model_package_group_policy tags", + "j": [ + "ModelPackageGroupPolicy" + ] + }, + "AWS::SageMaker::ModelQualityJobDefinition": { + "a": "endpoint_name job_definition_name job_resources model_quality_app_specification model_quality_baseline_config model_quality_job_input model_quality_job_output_config network_config role_arn stopping_condition tags", + "m": [ + "ModelQualityAppSpecification.Environment" + ] + }, + "AWS::SageMaker::MonitoringSchedule": { + "a": "endpoint_name failure_reason last_monitoring_execution_summary monitoring_schedule_config monitoring_schedule_name monitoring_schedule_status tags", + "m": [ + "MonitoringScheduleConfig.MonitoringJobDefinition.Environment" + ] + }, + "AWS::SageMaker::NotebookInstance": { + "a": "accelerator_types additional_code_repositories default_code_repository direct_internet_access instance_metadata_service_configuration instance_type kms_key_id lifecycle_config_name notebook_instance_name platform_identifier role_arn root_access security_group_ids subnet_id tags volume_size_in_gb" + }, + "AWS::SageMaker::NotebookInstanceLifecycleConfig": { + "a": "notebook_instance_lifecycle_config_name on_create on_start tags" + }, + "AWS::SageMaker::PartnerApp": { + "a": "app_version application_config auth_type client_token enable_auto_minor_version_upgrade enable_iam_session_based_identity execution_role_arn kms_key_id maintenance_config name tags tier type", + "m": [ + "ApplicationConfig.Arguments" + ] + }, + "AWS::SageMaker::Pipeline": { + "a": "parallelism_configuration pipeline_definition pipeline_description pipeline_display_name pipeline_name role_arn tags" + }, + "AWS::SageMaker::ProcessingJob": { + "a": "app_specification environment experiment_config network_config processing_inputs processing_job_name processing_output_config processing_resources role_arn stopping_condition tags", + "m": [ + "Environment" + ] + }, + "AWS::SageMaker::Project": { + "a": "project_description project_name service_catalog_provisioned_product_details service_catalog_provisioning_details tags template_provider_details" + }, + "AWS::SageMaker::Space": { + "a": "domain_id ownership_settings space_display_name space_name space_settings space_sharing_settings tags" + }, + "AWS::SageMaker::StudioLifecycleConfig": { + "a": "studio_lifecycle_config_app_type studio_lifecycle_config_content studio_lifecycle_config_name tags" + }, + "AWS::SageMaker::TrialComponent": { + "a": "display_name input_artifacts metadata_properties output_artifacts parameters status tags trial_component_name", + "m": [ + "InputArtifacts", + "OutputArtifacts", + "Parameters" + ] + }, + "AWS::SageMaker::UserProfile": { + "a": "domain_id single_sign_on_user_identifier single_sign_on_user_value tags user_profile_name user_settings" + }, + "AWS::SageMaker::Workforce": { + "a": "cognito_config ip_address_type oidc_config source_ip_config tags workforce_name workforce_vpc_config", + "m": [ + "OidcConfig.AuthenticationRequestExtraParams" + ] + }, + "AWS::SageMaker::Workteam": { + "a": "description member_definitions notification_configuration tags workforce_name workteam_name" + }, + "AWS::Scheduler::Schedule": { + "a": "description end_date flexible_time_window group_name kms_key_arn name schedule_expression schedule_expression_timezone start_date state target", + "x": [ + "Target.EventBridgePutEventsV2Parameters", + "Target.EventBridgePutRawEventsParameters" + ] + }, + "AWS::Scheduler::ScheduleGroup": { + "a": "name tags" + }, + "AWS::SecretsManager::ResourcePolicy": { + "a": "block_public_policy resource_policy secret_id", + "j": [ + "ResourcePolicy" + ] + }, + "AWS::SecretsManager::RotationSchedule": { + "a": "external_secret_rotation_metadata external_secret_rotation_role_arn hosted_rotation_lambda rotate_immediately_on_update rotation_lambda_arn rotation_rules secret_id" + }, + "AWS::SecretsManager::Secret": { + "a": "description generate_secret_string kms_key_id name replica_regions secret_string tags type" + }, + "AWS::SecretsManager::SecretTargetAttachment": { + "a": "secret_id target_id target_type" + }, + "AWS::SecurityAgent::AgentSpace": { + "a": "aws_resources code_review_settings description integrated_resources kms_key_id name tags target_domain_ids" + }, + "AWS::SecurityAgent::Application": { + "a": "default_kms_key_id id_c_configuration role_arn tags" + }, + "AWS::SecurityAgent::Artifact": { + "a": "agent_space_id artifact_content artifact_type file_name" + }, + "AWS::SecurityAgent::Integration": { + "a": "display_name kms_key_id private_connection_name provider_input provider_name tags", + "x": [ + "Provider" + ] + }, + "AWS::SecurityAgent::Pentest": { + "a": "agent_space_id assets ci_cd_configuration clean_up_strategy code_remediation_strategy disable_managed_skills exclude_risk_types log_config max_task_hours network_traffic_config report_destination report_filters service_role test_scope title vpc_config" + }, + "AWS::SecurityAgent::PrivateConnection": { + "a": "certificate mode private_connection_name tags" + }, + "AWS::SecurityAgent::SecurityRequirementPack": { + "a": "description kms_key_id name security_requirements status tags" + }, + "AWS::SecurityAgent::TargetDomain": { + "a": "tags target_domain_name verification_method" + }, + "AWS::SecurityHub::ActionTarget": { + "a": "action_target_id description name" + }, + "AWS::SecurityHub::AggregatorV2": { + "a": "linked_regions region_linking_mode tags", + "m": [ + "Tags" + ] + }, + "AWS::SecurityHub::AutomationRuleV2": { + "a": "actions criteria description rule_name rule_order rule_status tags", + "m": [ + "Tags" + ] + }, + "AWS::SecurityHub::ConfigurationPolicy": { + "a": "configuration_policy description name tags", + "m": [ + "ConfigurationPolicy.SecurityHub.SecurityControlsConfiguration.SecurityControlCustomParameters.Parameters", + "Tags" + ] + }, + "AWS::SecurityHub::Connector": { + "a": "description name provider_name tags", + "m": [ + "Tags" + ], + "x": [ + "Provider" + ] + }, + "AWS::SecurityHub::ConnectorV2": { + "a": "description kms_key_arn name provider_name tags", + "m": [ + "Tags" + ], + "x": [ + "Provider" + ] + }, + "AWS::SecurityHub::DelegatedAdmin": { + "a": "admin_account_id" + }, + "AWS::SecurityHub::FindingAggregator": { + "a": "region_linking_mode regions" + }, + "AWS::SecurityHub::Hub": { + "a": "auto_enable_controls control_finding_generator enable_default_standards tags", + "m": [ + "Tags" + ] + }, + "AWS::SecurityHub::HubV2": { + "a": "network_scanning tags", + "m": [ + "Tags" + ] + }, + "AWS::SecurityHub::Insight": { + "a": "filters group_by_attribute name", + "r": { + "Filters.ResourceAwsEc2InstanceIamInstanceProfileArn": "resource_aws_ec_2_instance_iam_instance_profile_arn", + "Filters.ResourceAwsEc2InstanceImageId": "resource_aws_ec_2_instance_image_id", + "Filters.ResourceAwsEc2InstanceIpV4Addresses": "resource_aws_ec_2_instance_ip_v4_addresses", + "Filters.ResourceAwsEc2InstanceIpV6Addresses": "resource_aws_ec_2_instance_ip_v6_addresses", + "Filters.ResourceAwsEc2InstanceKeyName": "resource_aws_ec_2_instance_key_name", + "Filters.ResourceAwsEc2InstanceLaunchedAt": "resource_aws_ec_2_instance_launched_at", + "Filters.ResourceAwsEc2InstanceSubnetId": "resource_aws_ec_2_instance_subnet_id", + "Filters.ResourceAwsEc2InstanceType": "resource_aws_ec_2_instance_type", + "Filters.ResourceAwsEc2InstanceVpcId": "resource_aws_ec_2_instance_vpc_id" + } + }, + "AWS::SecurityHub::OrganizationConfiguration": { + "a": "auto_enable auto_enable_standards configuration_type" + }, + "AWS::SecurityHub::PolicyAssociation": { + "a": "configuration_policy_id target_id target_type" + }, + "AWS::SecurityHub::ProductSubscription": { + "a": "product_arn" + }, + "AWS::SecurityHub::SecurityControl": { + "a": "last_update_reason parameters security_control_arn security_control_id", + "m": [ + "Parameters" + ] + }, + "AWS::SecurityHub::Standard": { + "a": "disabled_standards_controls standards_arn" + }, + "AWS::SecurityLake::AwsLogSource": { + "a": "accounts data_lake_arn source_name source_version" + }, + "AWS::SecurityLake::DataLake": { + "a": "encryption_configuration lifecycle_configuration meta_store_manager_role_arn replication_configuration tags" + }, + "AWS::SecurityLake::SubscriberNotification": { + "a": "notification_configuration subscriber_arn", + "j": [ + "NotificationConfiguration.SqsNotificationConfiguration" + ] + }, + "AWS::ServerlessRepo::Application": { + "a": "author description home_page_url labels license_body name readme_body semantic_version source_code_url spdx_license_id template_body" + }, + "AWS::ServiceCatalog::AcceptedPortfolioShare": { + "a": "accept_language portfolio_id" + }, + "AWS::ServiceCatalog::CloudFormationProduct": { + "a": "accept_language description distributor name owner product_type provisioning_artifact_parameters replace_provisioning_artifacts source_connection support_description support_email support_url tags" + }, + "AWS::ServiceCatalog::CloudFormationProvisionedProduct": { + "a": "accept_language notification_arns path_id path_name product_id product_name provisioned_product_name provisioning_artifact_id provisioning_artifact_name provisioning_parameters provisioning_preferences tags", + "m": [ + "Outputs" + ] + }, + "AWS::ServiceCatalog::LaunchNotificationConstraint": { + "a": "accept_language description notification_arns portfolio_id product_id" + }, + "AWS::ServiceCatalog::LaunchRoleConstraint": { + "a": "accept_language description local_role_name portfolio_id product_id role_arn" + }, + "AWS::ServiceCatalog::LaunchTemplateConstraint": { + "a": "accept_language description portfolio_id product_id rules" + }, + "AWS::ServiceCatalog::Portfolio": { + "a": "accept_language description display_name provider_name tags" + }, + "AWS::ServiceCatalog::PortfolioPrincipalAssociation": { + "a": "accept_language portfolio_id principal_arn principal_type" + }, + "AWS::ServiceCatalog::PortfolioProductAssociation": { + "a": "accept_language portfolio_id product_id source_portfolio_id" + }, + "AWS::ServiceCatalog::PortfolioShare": { + "a": "accept_language account_id portfolio_id share_tag_options" + }, + "AWS::ServiceCatalog::ResourceUpdateConstraint": { + "a": "accept_language description portfolio_id product_id tag_update_on_provisioned_product" + }, + "AWS::ServiceCatalog::ServiceAction": { + "a": "accept_language definition definition_type description name" + }, + "AWS::ServiceCatalog::ServiceActionAssociation": { + "a": "product_id provisioning_artifact_id service_action_id" + }, + "AWS::ServiceCatalog::StackSetConstraint": { + "a": "accept_language account_list admin_role description execution_role portfolio_id product_id region_list stack_instance_control" + }, + "AWS::ServiceCatalog::TagOption": { + "a": "active key value" + }, + "AWS::ServiceCatalog::TagOptionAssociation": { + "a": "resource_id tag_option_id" + }, + "AWS::ServiceCatalogAppRegistry::Application": { + "a": "description name tags", + "m": [ + "Tags" + ] + }, + "AWS::ServiceCatalogAppRegistry::AttributeGroup": { + "a": "attributes description name tags", + "j": [ + "Attributes" + ], + "m": [ + "Tags" + ] + }, + "AWS::ServiceCatalogAppRegistry::AttributeGroupAssociation": { + "a": "application attribute_group" + }, + "AWS::ServiceCatalogAppRegistry::ResourceAssociation": { + "a": "application resource resource_type" + }, + "AWS::ServiceDiscovery::HttpNamespace": { + "a": "description name tags" + }, + "AWS::ServiceDiscovery::Instance": { + "a": "instance_attributes instance_id service_id", + "j": [ + "InstanceAttributes" + ] + }, + "AWS::ServiceDiscovery::PrivateDnsNamespace": { + "a": "description name properties tags vpc" + }, + "AWS::ServiceDiscovery::PublicDnsNamespace": { + "a": "description name properties tags" + }, + "AWS::ServiceDiscovery::Service": { + "a": "description dns_config health_check_config health_check_custom_config name namespace_id service_attributes tags type", + "m": [ + "ServiceAttributes" + ] + }, + "AWS::Shield::DRTAccess": { + "a": "log_bucket_list role_arn" + }, + "AWS::Shield::ProactiveEngagement": { + "a": "emergency_contact_list proactive_engagement_status" + }, + "AWS::Shield::Protection": { + "a": "application_layer_automatic_response_configuration health_check_arns name resource_arn tags" + }, + "AWS::Shield::ProtectionGroup": { + "a": "aggregation members pattern protection_group_id resource_type tags" + }, + "AWS::Signer::ProfilePermission": { + "a": "action principal profile_name profile_version statement_id" + }, + "AWS::Signer::SigningProfile": { + "a": "platform_id signature_validity_period tags" + }, + "AWS::SimSpaceWeaver::Simulation": { + "a": "maximum_duration name role_arn schema_s3_location snapshot_s3_location" + }, + "AWS::StepFunctions::Activity": { + "a": "encryption_configuration name tags" + }, + "AWS::StepFunctions::StateMachine": { + "a": "definition definition_s3_location definition_string definition_substitutions logging_configuration role_arn state_machine_name state_machine_type tags tracing_configuration", + "j": [ + "Definition" + ], + "m": [ + "DefinitionSubstitutions" + ], + "x": [ + "EncryptionConfiguration", + "StateMachineRevisionId" + ] + }, + "AWS::StepFunctions::StateMachineAlias": { + "a": "deployment_preference description name routing_configuration state_machine_arn" + }, + "AWS::StepFunctions::StateMachineVersion": { + "a": "description state_machine_arn state_machine_revision_id" + }, + "AWS::StorageGateway::NFSFileShare": { + "a": "audit_destination_arn bucket_region cache_attributes client_list default_storage_class encryption_type file_share_name gateway_arn guess_mime_type_enabled kms_encrypted kms_key location_arn nfs_file_share_defaults notification_policy object_acl read_only requester_pays role squash tags vpc_endpoint_dns_name" + }, + "AWS::StorageGateway::SMBFileShare": { + "a": "access_based_enumeration admin_user_list audit_destination_arn authentication bucket_region cache_attributes case_sensitivity default_storage_class encryption_type file_share_name gateway_arn guess_mime_type_enabled invalid_user_list kms_encrypted kms_key location_arn notification_policy object_acl oplocks_enabled read_only requester_pays role smbacl_enabled tags valid_user_list vpc_endpoint_dns_name" + }, + "AWS::StorageGateway::Tape": { + "a": "gateway_arn kms_encrypted kms_key pool_id tags tape_barcode tape_size_in_bytes worm" + }, + "AWS::StorageGateway::TapePool": { + "a": "pool_name retention_lock_time_in_days retention_lock_type storage_class tags" + }, + "AWS::StorageGateway::Volume": { + "a": "gateway_arn kms_encrypted kms_key network_interface_id snapshot_id source_volume_arn tags target_name volume_size_in_bytes" + }, + "AWS::SupportApp::AccountAlias": { + "a": "account_alias" + }, + "AWS::SupportApp::SlackChannelConfiguration": { + "a": "channel_id channel_name channel_role_arn notify_on_add_correspondence_to_case notify_on_case_severity notify_on_create_or_reopen_case notify_on_resolve_case team_id" + }, + "AWS::SupportApp::SlackWorkspaceConfiguration": { + "a": "team_id version_id" + }, + "AWS::SupportAuthZ::SupportPermit": { + "a": "description name permit signing_key_info support_case_display_id tags", + "j": [ + "Permit.Actions.AllActions", + "Permit.Resources.AllResourcesInRegion" + ] + }, + "AWS::Synthetics::Canary": { + "a": "artifact_config artifact_s3_location browser_configs code delete_lambda_resources_on_canary_deletion dry_run_and_update execution_role_arn failure_retention_period name provisioned_resource_cleanup resources_to_replicate_tags run_config runtime_version schedule start_canary_after_creation success_retention_period tags visual_reference visual_references vpc_config", + "m": [ + "RunConfig.EnvironmentVariables" + ], + "x": [ + "KmsKeyArn", + "Replicas" + ] + }, + "AWS::Synthetics::Group": { + "a": "name resource_arns tags" + }, + "AWS::SystemsManagerSAP::Application": { + "a": "application_id application_type components_info credentials database_arn instances sap_instance_number sid tags", + "r": { + "ComponentsInfo.Ec2InstanceId": "ec_2_instance_id" + } + }, + "AWS::Textract::Adapter": { + "a": "adapter_name auto_update description feature_types tags" + }, + "AWS::Timestream::Database": { + "a": "database_name kms_key_id tags" + }, + "AWS::Timestream::InfluxDBBackup": { + "a": "db_resource_id name retention_days tags" + }, + "AWS::Timestream::InfluxDBCluster": { + "a": "allocated_storage bucket db_instance_type db_parameter_group_identifier db_storage_type deployment_type failover_mode kms_key_id log_delivery_configuration maintenance_schedule name network_type organization password port publicly_accessible tags username vpc_security_group_ids vpc_subnet_ids" + }, + "AWS::Timestream::InfluxDBInstance": { + "a": "allocated_storage bucket db_instance_type db_parameter_group_identifier db_storage_type deployment_type kms_key_id log_delivery_configuration maintenance_schedule name network_type organization password port publicly_accessible tags username vpc_security_group_ids vpc_subnet_ids" + }, + "AWS::Timestream::ScheduledQuery": { + "a": "client_token error_report_configuration kms_key_id notification_configuration query_string schedule_configuration scheduled_query_execution_role_arn scheduled_query_name tags target_configuration" + }, + "AWS::Timestream::Table": { + "a": "database_name magnetic_store_write_properties retention_properties schema table_name tags" + }, + "AWS::Transcribe::CallAnalyticsCategory": { + "a": "category_name input_type rules tags" + }, + "AWS::Transcribe::MedicalVocabulary": { + "a": "language_code tags vocabulary_file_uri vocabulary_name" + }, + "AWS::Transcribe::Vocabulary": { + "a": "data_access_role_arn language_code phrases tags vocabulary_file_uri vocabulary_name" + }, + "AWS::Transcribe::VocabularyFilter": { + "a": "data_access_role_arn language_code tags vocabulary_filter_file_uri vocabulary_filter_name words" + }, + "AWS::Transfer::Agreement": { + "a": "access_role base_directory custom_directories description enforce_message_signing local_profile_id partner_profile_id preserve_filename server_id status tags" + }, + "AWS::Transfer::Certificate": { + "a": "active_date certificate certificate_chain description inactive_date private_key tags usage" + }, + "AWS::Transfer::Connector": { + "a": "access_role as_2_config egress_config egress_type ip_address_type logging_role security_policy_name sftp_config tags url" + }, + "AWS::Transfer::HostKey": { + "a": "description host_key_body kms_key server_id storage_type tags" + }, + "AWS::Transfer::Profile": { + "a": "as_2_id certificate_ids profile_type tags" + }, + "AWS::Transfer::Server": { + "a": "certificate create_with_host_key domain endpoint_details endpoint_type identity_provider_details identity_provider_type ip_address_type logging_role post_authentication_login_banner pre_authentication_login_banner protocol_details protocols s3_storage_options security_policy_name structured_log_destinations tags workflow_details" + }, + "AWS::Transfer::WebApp": { + "a": "access_endpoint endpoint_details identity_provider_details tags web_app_customization web_app_endpoint_policy web_app_units" + }, + "AWS::Transfer::Workflow": { + "a": "description on_exception_steps steps structured_log_destinations tags" + }, + "AWS::Translate::ParallelData": { + "a": "description encryption_key name parallel_data_config tags" + }, + "AWS::Translate::Terminology": { + "a": "description encryption_key merge_strategy name tags terminology_data" + }, + "AWS::UXC::AccountCustomization": { + "a": "account_color visible_regions visible_services" + }, + "AWS::VerifiedPermissions::IdentitySource": { + "a": "configuration policy_store_id principal_entity_type" + }, + "AWS::VerifiedPermissions::Policy": { + "a": "definition name policy_store_id" + }, + "AWS::VerifiedPermissions::PolicyStore": { + "a": "deletion_protection description encryption_settings schema tags validation_settings" + }, + "AWS::VerifiedPermissions::PolicyStoreAlias": { + "a": "alias_name policy_store_id" + }, + "AWS::VerifiedPermissions::PolicyTemplate": { + "a": "description name policy_store_id statement" + }, + "AWS::VoiceID::Domain": { + "a": "description name server_side_encryption_configuration tags" + }, + "AWS::VpcLattice::AccessLogSubscription": { + "a": "destination_arn resource_identifier service_network_log_type tags" + }, + "AWS::VpcLattice::AuthPolicy": { + "a": "policy resource_identifier", + "j": [ + "Policy" + ] + }, + "AWS::VpcLattice::Listener": { + "a": "default_action name port protocol service_identifier tags" + }, + "AWS::VpcLattice::ResourceConfiguration": { + "a": "allow_association_to_sharable_service_network custom_domain_name domain_verification_id group_domain name port_ranges protocol_type resource_configuration_auth_type resource_configuration_definition resource_configuration_group_id resource_configuration_type resource_gateway_id tags" + }, + "AWS::VpcLattice::ResourceGateway": { + "a": "ip_address_type ipv_4_addresses_per_eni name resource_config_dns_resolution security_group_ids subnet_ids tags vpc_identifier" + }, + "AWS::VpcLattice::ResourcePolicy": { + "a": "policy resource_arn", + "j": [ + "Policy" + ] + }, + "AWS::VpcLattice::Rule": { + "a": "action listener_identifier match name priority service_identifier tags" + }, + "AWS::VpcLattice::Service": { + "a": "auth_type certificate_arn custom_domain_name dns_entry idle_timeout_seconds name tags" + }, + "AWS::VpcLattice::ServiceNetwork": { + "a": "auth_type name sharing_config tags" + }, + "AWS::VpcLattice::ServiceNetworkResourceAssociation": { + "a": "private_dns_enabled resource_configuration_id service_network_id tags" + }, + "AWS::VpcLattice::ServiceNetworkServiceAssociation": { + "a": "dns_entry service_identifier service_network_identifier tags" + }, + "AWS::VpcLattice::ServiceNetworkVpcAssociation": { + "a": "dns_options private_dns_enabled security_group_ids service_network_identifier tags vpc_identifier" + }, + "AWS::WAFv2::IPSet": { + "a": "addresses description ip_address_version name scope tags" + }, + "AWS::WAFv2::LoggingConfiguration": { + "a": "log_destination_configs logging_filter redacted_fields resource_arn", + "j": [ + "RedactedFields.Method", + "RedactedFields.QueryString", + "RedactedFields.UriPath" + ] + }, + "AWS::WAFv2::RegexPatternSet": { + "a": "description name regular_expression_list scope tags" + }, + "AWS::WAFv2::WebACLAssociation": { + "a": "resource_arn web_acl_arn" + }, + "AWS::WellArchitected::AgentContext": { + "a": "content context_type profile_arn title", + "j": [ + "Content" + ] + }, + "AWS::WellArchitected::AgentGoal": { + "a": "description pillars profile_arn title" + }, + "AWS::WellArchitected::AgentOrganizationalProfile": { + "a": "business_overview deletion_protection description display_name name pillars tags" + }, + "AWS::WellArchitected::AgentProfile": { + "a": "aggregation_configuration business_overview deletion_protection description display_name execution_role_arn name pillars tags" + }, + "AWS::WellArchitected::AgentProfilePolicy": { + "a": "policy profile_arn" + }, + "AWS::WellArchitected::Lens": { + "a": "json_string lens_version tags" + }, + "AWS::WellArchitected::Profile": { + "a": "profile_description profile_name profile_questions tags" + }, + "AWS::WellArchitected::ReviewTemplate": { + "a": "description lenses notes tags template_name" + }, + "AWS::WellArchitected::Workload": { + "a": "account_ids architectural_design aws_regions description discovery_config environment industry industry_type lenses non_aws_regions notes review_owner tags workload_name" + }, + "AWS::Wickr::Network": { + "a": "access_level network_name" + }, + "AWS::Wisdom::AIAgent": { + "a": "assistant_id configuration description name tags type", + "m": [ + "Tags" + ] + }, + "AWS::Wisdom::AIAgentVersion": { + "a": "ai_agent_id assistant_id modified_time_seconds" + }, + "AWS::Wisdom::AIGuardrail": { + "a": "assistant_id blocked_input_messaging blocked_outputs_messaging content_policy_config contextual_grounding_policy_config description name sensitive_information_policy_config tags topic_policy_config word_policy_config", + "m": [ + "Tags" + ] + }, + "AWS::Wisdom::AIGuardrailVersion": { + "a": "ai_guardrail_id assistant_id modified_time_seconds" + }, + "AWS::Wisdom::AIPrompt": { + "a": "api_format assistant_id description model_id name tags template_configuration template_type type", + "m": [ + "Tags" + ], + "x": [ + "InferenceConfiguration" + ] + }, + "AWS::Wisdom::AIPromptVersion": { + "a": "ai_prompt_id assistant_id modified_time_seconds" + }, + "AWS::Wisdom::Assistant": { + "a": "description name server_side_encryption_configuration tags type" + }, + "AWS::Wisdom::AssistantAssociation": { + "a": "assistant_id association association_type tags" + }, + "AWS::Wisdom::Content": { + "a": "knowledge_base_id metadata name override_link_out_uri tags title upload_id", + "m": [ + "Metadata" + ] + }, + "AWS::Wisdom::ContentAssociation": { + "a": "association association_type content_id knowledge_base_id tags" + }, + "AWS::Wisdom::KnowledgeBase": { + "a": "description knowledge_base_type name rendering_configuration server_side_encryption_configuration source_configuration tags vector_ingestion_configuration" + }, + "AWS::Wisdom::MessageTemplate": { + "a": "channel_subtype content default_attributes description grouping_configuration knowledge_base_arn language message_template_attachments name tags", + "m": [ + "DefaultAttributes.CustomAttributes", + "DefaultAttributes.CustomerProfileAttributes.Custom" + ] + }, + "AWS::Wisdom::MessageTemplateVersion": { + "a": "message_template_arn message_template_content_sha_256" + }, + "AWS::Wisdom::QuickResponse": { + "a": "channels content content_type description grouping_configuration is_active knowledge_base_arn language name shortcut_key tags" + }, + "AWS::WorkSpaces::ConnectionAlias": { + "a": "connection_string tags" + }, + "AWS::WorkSpaces::Directory": { + "a": "active_directory_config certificate_based_auth_properties enable_self_service endpoint_encryption_mode idc_instance_arn ip_group_ids microsoft_entra_config saml_properties selfservice_permissions streaming_properties subnet_ids tags tenancy user_identity_type workspace_access_properties workspace_creation_properties workspace_directory_description workspace_directory_name workspace_type" + }, + "AWS::WorkSpaces::WorkspaceIpGroup": { + "a": "group_desc group_name tags user_rules" + }, + "AWS::WorkSpaces::WorkspacesPool": { + "a": "application_settings bundle_id capacity description directory_id pool_name running_mode tags timeout_settings" + }, + "AWS::WorkSpacesThinClient::Environment": { + "a": "desired_software_set_id desktop_arn desktop_endpoint device_creation_tags kms_key_arn maintenance_window name software_set_update_mode software_set_update_schedule tags" + }, + "AWS::WorkSpacesWeb::BrowserSettings": { + "a": "additional_encryption_context browser_policy customer_managed_key tags web_content_filtering_policy", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::WorkSpacesWeb::DataProtectionSettings": { + "a": "additional_encryption_context customer_managed_key description display_name inline_redaction_configuration tags", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::WorkSpacesWeb::IdentityProvider": { + "a": "identity_provider_details identity_provider_name identity_provider_type portal_arn tags", + "m": [ + "IdentityProviderDetails" + ] + }, + "AWS::WorkSpacesWeb::IpAccessSettings": { + "a": "additional_encryption_context customer_managed_key description display_name ip_rules tags", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::WorkSpacesWeb::NetworkSettings": { + "a": "security_group_ids subnet_ids tags vpc_id" + }, + "AWS::WorkSpacesWeb::Portal": { + "a": "additional_encryption_context authentication_type browser_settings_arn customer_managed_key data_protection_settings_arn display_name instance_type ip_access_settings_arn max_concurrent_sessions network_settings_arn portal_custom_domain session_logger_arn tags trust_store_arn user_access_logging_settings_arn user_settings_arn", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::WorkSpacesWeb::SessionLogger": { + "a": "additional_encryption_context customer_managed_key display_name event_filter log_configuration tags", + "m": [ + "AdditionalEncryptionContext" + ] + }, + "AWS::WorkSpacesWeb::TrustStore": { + "a": "certificate_list tags" + }, + "AWS::WorkSpacesWeb::UserAccessLoggingSettings": { + "a": "kinesis_stream_arn tags" + }, + "AWS::WorkSpacesWeb::UserSettings": { + "a": "additional_encryption_context branding_configuration cookie_synchronization_configuration copy_allowed customer_managed_key deep_link_allowed disconnect_timeout_in_minutes download_allowed idle_disconnect_timeout_in_minutes paste_allowed print_allowed tags toolbar_configuration upload_allowed web_authn_allowed", + "m": [ + "AdditionalEncryptionContext", + "BrandingConfiguration.LocalizedStrings" + ] + }, + "AWS::WorkspacesInstances::Volume": { + "a": "availability_zone encrypted iops kms_key_id size_in_gb snapshot_id tag_specifications throughput volume_type" + }, + "AWS::WorkspacesInstances::VolumeAssociation": { + "a": "device disassociate_mode volume_id workspace_instance_id" + }, + "AWS::WorkspacesInstances::WorkspaceInstance": { + "a": "managed_instance tags" + }, + "AWS::XRay::Group": { + "a": "filter_expression group_name insights_configuration tags" + }, + "AWS::XRay::ResourcePolicy": { + "a": "bypass_policy_lockout_check policy_document policy_name" + }, + "AWS::XRay::SamplingRule": { + "a": "rule_name sampling_rule sampling_rule_record sampling_rule_update tags", + "m": [ + "SamplingRule.Attributes", + "SamplingRuleRecord.SamplingRule.Attributes", + "SamplingRuleUpdate.Attributes" + ] + }, + "AWS::XRay::TransactionSearchConfig": { + "a": "cloudwatch_logs_configuration indexing_percentage" + } +} diff --git a/services/converter-api/converters/cfn/builder.py b/services/converter-api/converters/cfn/builder.py new file mode 100644 index 0000000..d0fe4b8 --- /dev/null +++ b/services/converter-api/converters/cfn/builder.py @@ -0,0 +1,337 @@ +"""Building one Terraform resource from one CloudFormation resource. + +A converter takes properties out of `Props` one at a time (`take`, `attr`, `block`). What is +left when it returns was not converted: it stays in the output as a comment and is reported +in the notes. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from typing import Any + +from converters.cfn import hcl +from converters.cfn.context import Context +from converters.cfn.expressions import intrinsic_name +from converters.cfn.models import BLANK, Attr, Block, Comment, Raw, ResourceInfo + +# Marks "no value given", where None is a value. +MISSING: Any = object() +SNIPPET_LENGTH = 120 + + +def snippet(value: Any) -> str: + """A short JSON rendering of a value, for a comment.""" + text = json.dumps(value, default=str, separators=(", ", ": ")) + return text if len(text) <= SNIPPET_LENGTH else text[: SNIPPET_LENGTH - 3] + "..." + + +def tags_map(ctx: Context, value: Any) -> Any: + """[{Key, Value}, ...] or {key: value} as a map. A computed list becomes a for + expression.""" + if isinstance(value, dict) and intrinsic_name(value) is None: + return {str(name): ctx.expr(item) for name, item in value.items()} + literal_tags = isinstance(value, list) and all( + isinstance(tag, dict) and "Key" in tag and intrinsic_name(tag) is None for tag in value + ) + if literal_tags: + result: dict[Any, Any] = {} + for tag in value: + tag_key = ctx.expr(tag["Key"]) + name = tag_key if isinstance(tag_key, str) else Raw(hcl.inline(tag_key)) + result[name] = ctx.expr(tag.get("Value", "")) + return result + return Raw(f"{{ for tag in {ctx.text(value)} : tag.Key => tag.Value }}") + + +class Props: + """The properties of a resource, or of one nested CloudFormation structure, on their way + to the items of an HCL body.""" + + def __init__(self, ctx: Context, values: Any, where: str, owner: str) -> None: + """Properties `values`, found at `where` ("MyBucket.VersioningConfiguration") in + `owner` ("MyBucket (AWS::S3::Bucket)"); both are for notes.""" + self.ctx = ctx + self.values: dict[str, Any] = dict(values) if isinstance(values, dict) else {} + self.where = where + self.owner = owner + self.items: list[Any] = [] + + # --- reading ------------------------------------------------------------------------ + + def has(self, name: str) -> bool: + """Whether the property is present with a value.""" + value = self.values.get(name, MISSING) + return value is not MISSING and value is not None and not self.ctx.is_no_value(value) + + def peek(self, name: str, default: Any = None) -> Any: + """A property, left in place.""" + return self.values.get(name, default) + + def take(self, name: str, default: Any = None) -> Any: + """Remove and return a property (`default` when it is absent or AWS::NoValue).""" + value = self.values.pop(name, MISSING) + if value is MISSING or value is None or self.ctx.is_no_value(value): + return default + return value + + def literal(self, name: str, kind: type, value: Any = MISSING) -> Any: + """A property that must be a literal list or mapping (`kind`) for the converter to + look inside it, taken from the properties unless `value` is given. When it is a + function (`!If`, `!Ref`...) instead, it is noted and kept as a comment and None is + returned, so callers never mistake an intrinsic for data.""" + if value is MISSING: + value = self.take(name) + is_data = isinstance(value, kind) and not ( + isinstance(value, dict) and intrinsic_name(value) is not None + ) + if value is None or is_data: + return value + self.ctx.note( + f"{self.owner}: '{self.where}.{name}' is computed by a function and was not " + "converted; set it by hand" + ) + self.comment(f"{name} was not converted: {snippet(value)}") + return None + + def drop(self, name: str) -> None: + """Remove a property the converter covers another way.""" + self.values.pop(name, None) + + # --- value conversions, for attr() -------------------------------------------------- + + def as_number(self, value: Any) -> Any: + """A number from a number or numeric text; anything else as an expression.""" + if isinstance(value, str): + try: + number = float(value) + except ValueError: + return value + return int(number) if number.is_integer() else number + return self.ctx.expr(value) + + def as_bool(self, value: Any) -> Any: + """A boolean from a boolean or "true"/"false"; anything else as an expression.""" + if isinstance(value, str) and value.lower() in ("true", "false"): + return value.lower() == "true" + return self.ctx.expr(value) + + def as_list(self, value: Any) -> Any: + """A list, also when CloudFormation gives one value.""" + converted = self.ctx.expr(value) + if isinstance(value, list) or isinstance(converted, Raw | list): + return converted + return [converted] + + # --- writing ------------------------------------------------------------------------ + + def set(self, tf_name: str, value: Any) -> None: + """Add `tf_name = value`.""" + self.items.append(Attr(tf_name, value)) + + def comment(self, text: str) -> None: + """Add a comment line.""" + self.items.append(Comment(text)) + + def attr( + self, tf_name: str, cfn_name: str, convert: Callable[[Any], Any] | None = None + ) -> bool: + """Copy a property to an attribute when it is present, through `convert` when given + (default: as an expression). Returns whether it was present.""" + if not self.has(cfn_name): + self.values.pop(cfn_name, None) + return False + value = self.values.pop(cfn_name) + self.set(tf_name, convert(value) if convert else self.ctx.expr(value)) + return True + + def attrs(self, mapping: dict[str, str]) -> None: + """Copy several properties: {tf_name: cfn_name}.""" + for tf_name, cfn_name in mapping.items(): + self.attr(tf_name, cfn_name) + + def number(self, tf_name: str, cfn_name: str) -> bool: + """A numeric property, with numeric text turned into a number.""" + return self.attr(tf_name, cfn_name, self.as_number) + + def boolean(self, tf_name: str, cfn_name: str) -> bool: + """A boolean property, with "true"/"false" turned into a boolean.""" + return self.attr(tf_name, cfn_name, self.as_bool) + + def json(self, tf_name: str, cfn_name: str) -> bool: + """A JSON document property, as jsonencode().""" + return self.attr(tf_name, cfn_name, self.ctx.json) + + def list_attr(self, tf_name: str, cfn_name: str) -> bool: + """A property that is a list in Terraform, also when CloudFormation gives one value.""" + return self.attr(tf_name, cfn_name, self.as_list) + + def tags(self, cfn_name: str = "Tags", tf_name: str = "tags") -> None: + """CloudFormation tags ([{Key, Value}] or a map) as a Terraform tags map.""" + if not self.has(cfn_name): + self.values.pop(cfn_name, None) + return + self.set(tf_name, tags_map(self.ctx, self.values.pop(cfn_name))) + + def block(self, tf_name: str, cfn_name: str, fill: Callable[[Props], None]) -> bool: + """A nested structure, or a list of them, as nested blocks filled by `fill`.""" + if not self.has(cfn_name): + self.values.pop(cfn_name, None) + return False + value = self.values.pop(cfn_name) + self.add_blocks(tf_name, value, fill, f"{self.where}.{cfn_name}") + return True + + def add_blocks( + self, tf_name: str, value: Any, fill: Callable[[Props], None], where: str + ) -> None: + """One block per structure in `value`. An `!If` with an AWS::NoValue branch becomes + a dynamic block; any other function is noted and kept as a comment.""" + if isinstance(value, list): + for index, item in enumerate(value): + self.add_blocks(tf_name, item, fill, f"{where}[{index}]") + return + if isinstance(value, dict) and intrinsic_name(value) == "Fn::If": + if self.dynamic_block(tf_name, value["Fn::If"], fill, where): + return + if not isinstance(value, dict) or intrinsic_name(value) is not None: + self.ctx.note( + f"{self.owner}: '{where}' is computed by a function, so it was not turned into " + "Terraform blocks; set it by hand" + ) + self.comment(f"{where.split('.', 1)[-1]} was not converted: {snippet(value)}") + return + inner = Props(self.ctx, value, where, self.owner) + fill(inner) + inner.finish() + self.items.append(Block(tf_name, [], inner.items)) + + def dynamic_block( + self, tf_name: str, args: Any, fill: Callable[[Props], None], where: str + ) -> bool: + """`!If [Cond, {...}, !Ref AWS::NoValue]` as a dynamic block present only when the + condition holds. Returns whether `args` had that shape.""" + if not isinstance(args, list) or len(args) != 3: + return False + name, yes, no = args + if self.ctx.is_no_value(no) and isinstance(yes, dict): + condition, body = self.ctx.condition(name), yes + elif self.ctx.is_no_value(yes) and isinstance(no, dict): + condition, body = f"!{self.ctx.condition(name)}", no + else: + return False + inner = Props(self.ctx, body, where, self.owner) + fill(inner) + inner.finish() + for_each = Attr("for_each", Raw(f"{condition} ? [1] : []")) + content = Block("content", [], inner.items) + self.items.append(Block("dynamic", [tf_name], [for_each, content])) + return True + + def finish(self) -> None: + """Report, and keep as comments, every property nobody took.""" + for name, value in self.values.items(): + if value is None or self.ctx.is_no_value(value): + continue + path = f"{self.where}.{name}" + self.ctx.note(f"{self.owner}: property '{path}' was not converted; set it by hand") + self.comment(f"{name} was not converted: {snippet(value)}") + self.values.clear() + + +class Builder: + """One CloudFormation resource on its way to one or more Terraform blocks.""" + + def __init__( + self, + ctx: Context, + info: ResourceInfo, + resource: dict[str, Any], + hints: dict[str, Any] | None = None, + ) -> None: + """A builder for `resource`, going to `info`. `hints` carry facts the SAM or CDK + step found, such as a local code folder.""" + self.ctx = ctx + self.info = info + self.resource = resource + self.hints: dict[str, Any] = hints if hints is not None else {} + owner = f"{info.logical_id} ({info.cfn_type})" + self.props = Props(ctx, resource.get("Properties") or {}, info.logical_id, owner) + self.extra: list[Block] = [] + self.lifecycle: list[Any] = [] + # A condition the main resource exists under, on top of its own Condition. + self.main_when: str | None = None + + @property + def logical_id(self) -> str: + """The resource's logical ID.""" + return self.info.logical_id + + def self_ref(self, attribute: str) -> Raw: + """An expression reading one of this resource's attributes.""" + return Raw(self.info.expression(attribute)) + + def count_items(self, when: str | None = None) -> list[Any]: + """`count = ...` for a resource with a Condition, or one that exists only `when` an + expression holds (an `!If [C, x, !Ref AWS::NoValue]` list item). None of either + gives no items.""" + condition = self.resource.get("Condition") + parts = [self.ctx.condition(condition)] if condition else [] + if when: + parts.append(when if not parts else f"({when})") + if not parts: + return [] + return [Attr("count", Raw(f"{' && '.join(parts)} ? 1 : 0")), BLANK] + + def main_count_items(self) -> list[Any]: + """The count items of the main resource.""" + return self.count_items(self.main_when) + + def name_attr(self, tf_name: str, cfn_name: str, lowercase: bool = False) -> None: + """A name Terraform requires and CloudFormation generates when it is left out. + CloudFormation uses '--'; this uses '-'.""" + if self.props.attr(tf_name, cfn_name): + return + self.ctx.stack_name_used = True + suffix = self.logical_id.lower() if lowercase else self.logical_id + self.props.set(tf_name, Raw(f'"${{var.stack_name}}-{hcl.template_text(suffix)}"')) + self.ctx.note( + f"{self.logical_id} had no {cfn_name}, so CloudFormation generated one; Terraform " + f"needs it, so it is now '-{suffix}' (to adopt the existing resource, " + "use its current name)" + ) + + def extra_name(self, suffix: str) -> str: + """The main name plus a suffix, saying the main name once: a policy named + 'MyRolePolicy' on 'MyRole' is 'my_role_policy'.""" + if not suffix: + return self.info.name + repeated = f"_{self.info.name}_" + if suffix.startswith(repeated): + suffix = suffix[len(repeated) - 1 :] + return f"{self.info.name}{suffix}" + + def add_data(self, kind: str, suffix: str, items: list[Any]) -> str: + """A data source belonging to this resource, such as archive_file for Lambda code. + Returns its address.""" + name = self.ctx.names_for(f"data.{kind}").take(self.extra_name(suffix)) + self.extra.append(Block("data", [kind, name], self.count_items() + items)) + index = "[0]" if self.resource.get("Condition") else "" + return f"data.{kind}.{name}{index}" + + def add_resource( + self, + tf_type: str, + suffix: str, + items: list[Any], + counted: bool = True, + when: str | None = None, + ) -> str: + """An extra resource next to the main one, such as aws_s3_bucket_versioning. Returns + its address. It shares the main resource's Condition unless counted=False; `when` + adds a condition of its own (see ExpressionConverter.optional_item).""" + name = self.ctx.names_for(tf_type).take(self.extra_name(suffix)) + body = (self.count_items(when) if counted else []) + items + self.extra.append(Block("resource", [tf_type, name], body)) + return f"{tf_type}.{name}" diff --git a/services/converter-api/converters/cfn/cdk.py b/services/converter-api/converters/cfn/cdk.py new file mode 100644 index 0000000..e09dad3 --- /dev/null +++ b/services/converter-api/converters/cfn/cdk.py @@ -0,0 +1,294 @@ +"""Templates synthesized by the AWS CDK (`cdk synth`): remove the bookkeeping of the CDK, +name Terraform resources after their construct paths and point Lambda code at the cdk.out +asset folders. + +The converter never runs CDK code: the user runs `cdk synth` and sends the template it +writes. +""" + +from __future__ import annotations + +import copy +import re +from typing import Any + +from converters.cfn.cdk_constants import ( + AUTO_DELETE, + AUTO_DELETE_TAG, + BOOTSTRAP_PARAMETER, + BOOTSTRAP_RULE, + HANDLED, + LOG_RETENTION, + METADATA_CONDITION, + METADATA_TYPE, + NON_WORD, + PATH_SUFFIXES, + SUB_NAME, +) + + +def path_name(path: str) -> str | None: + """'MyStack/Api/Handler/Resource' -> 'Api_Handler'.""" + parts = [p for p in path.split("/")[1:] if p] + while parts and parts[-1] in PATH_SUFFIXES: + parts.pop() + if not parts: + return None + return "_".join(NON_WORD.sub("_", part).strip("_") for part in parts if part.strip("_")) + + +def references(value: Any, names: set[str]) -> bool: + """Whether `value` refers (Ref, Fn::GetAtt, Fn::Sub) to any of `names`.""" + if isinstance(value, dict): + if set(value) == {"Ref"}: + return value["Ref"] in names + if set(value) == {"Fn::GetAtt"}: + target = value["Fn::GetAtt"] + first = target[0] if isinstance(target, list) and target else str(target).split(".")[0] + return first in names + if set(value) == {"Fn::Sub"}: + text = value["Fn::Sub"][0] if isinstance(value["Fn::Sub"], list) else value["Fn::Sub"] + if isinstance(text, str) and any( + re.search(r"\$\{" + re.escape(n) + r"[.}]", text) for n in names + ): + return True + return any(references(v, names) for v in value.values()) + if isinstance(value, list): + return any(references(v, names) for v in value) + return False + + +def get_att_target(resource: dict[str, Any], prop: str) -> str | None: + """The logical id in a `Fn::GetAtt` held by property `prop` of `resource`.""" + value = (resource.get("Properties") or {}).get(prop) + if isinstance(value, dict) and "Fn::GetAtt" in value: + target = value["Fn::GetAtt"] + return target[0] if isinstance(target, list) else str(target).split(".")[0] + return None + + +def mentions_condition(value: Any, name: str) -> bool: + """Whether `value` uses condition `name` (a Condition attribute or Fn::If).""" + if isinstance(value, dict): + if value.get("Condition") == name: + return True + if ( + "Fn::If" in value + and isinstance(value["Fn::If"], list) + and value["Fn::If"][:1] == [name] + ): + return True + return any(mentions_condition(v, name) for v in value.values()) + if isinstance(value, list): + return any(mentions_condition(v, name) for v in value) + return False + + +def uses_condition(template: dict[str, Any], name: str) -> bool: + """Whether a resource, output or other condition of `template` uses condition `name`.""" + others = {k: v for k, v in (template.get("Conditions") or {}).items() if k != name} + return ( + mentions_condition(template["Resources"], name) + or mentions_condition(template.get("Outputs") or {}, name) + or mentions_condition(others, name) + ) + + +def referenced_ids(value: Any) -> set[str]: + """Every logical id `value` refers to through Ref, Fn::GetAtt or Fn::Sub, in one walk.""" + found: set[str] = set() + stack = [value] + while stack: + node = stack.pop() + if isinstance(node, dict): + if set(node) == {"Ref"} and isinstance(node["Ref"], str): + found.add(node["Ref"]) + elif set(node) == {"Fn::GetAtt"}: + target = node["Fn::GetAtt"] + first = target[0] if isinstance(target, list) and target else str(target) + found.add(str(first).split(".")[0]) + elif set(node) == {"Fn::Sub"}: + args = node["Fn::Sub"] + text = args[0] if isinstance(args, list) and args else args + if isinstance(text, str): + found.update(m.split(".")[0] for m in SUB_NAME.findall(text)) + stack.extend(node.values()) + elif isinstance(node, list): + stack.extend(node) + return found + + +def drop_tag(resource: dict[str, Any], key: str) -> None: + """Remove the tag `key` from a resource with a [{Key, Value}] tag list.""" + props = resource.get("Properties") or {} + tags = props.get("Tags") + if isinstance(tags, list): + kept = [t for t in tags if not (isinstance(t, dict) and t.get("Key") == key)] + if kept: + props["Tags"] = kept + else: + props.pop("Tags") + + +def clean_references(template: dict[str, Any], removed: set[str]) -> None: + """DependsOn entries and bucket policy statements that pointed at removed resources.""" + if not removed: + return + empty_policies = [] + for logical_id, resource in template["Resources"].items(): + depends = resource.get("DependsOn") + if depends is not None: + kept = [ + d for d in (depends if isinstance(depends, list) else [depends]) if d not in removed + ] + if kept: + resource["DependsOn"] = kept + else: + resource.pop("DependsOn") + if resource.get("Type") == "AWS::S3::BucketPolicy": + document = (resource.get("Properties") or {}).get("PolicyDocument") + if isinstance(document, dict) and isinstance(document.get("Statement"), list): + document["Statement"] = [ + s for s in document["Statement"] if not references(s, removed) + ] + if not document["Statement"]: + empty_policies.append(logical_id) + for logical_id in empty_policies: + del template["Resources"][logical_id] + + +def drop_entry(template: dict[str, Any], section: str, name: str) -> None: + """Remove `name` from a top-level section, and the section once it is empty.""" + entries = template.get(section) or {} + if name in entries: + del entries[name] + if not entries: + template.pop(section) + + +class CdkTemplate: + """One synthesized template being cleaned up for the converter.""" + + def __init__(self, template: dict[str, Any], notes: list[str]) -> None: + """Work on a copy of `template`; notes go to `notes`.""" + self.template = copy.deepcopy(template) + self.notes = notes + self.resources: dict[str, dict[str, Any]] = self.template["Resources"] + self.hints: dict[str, dict[str, Any]] = {} + self.names: dict[str, str] = {} + self.removed: set[str] = set() + + def prepare(self) -> tuple[dict[str, Any], dict[str, str], dict[str, dict[str, Any]]]: + """Returns (template, wanted Terraform names by logical id, converter hints).""" + self.drop_bookkeeping() + for logical_id, resource in list(self.resources.items()): + if resource.get("Type") in HANDLED: + self.replace_custom_resource(logical_id, resource) + self.remove_unused() + self.name_resources() + if METADATA_CONDITION in (self.template.get("Conditions") or {}) and not uses_condition( + self.template, METADATA_CONDITION + ): + drop_entry(self.template, "Conditions", METADATA_CONDITION) + return self.template, self.names, self.hints + + def drop_bookkeeping(self) -> None: + """CDK bookkeeping: version metadata and the bootstrap version check.""" + for logical_id, resource in self.resources.items(): + if resource.get("Type") == METADATA_TYPE: + self.removed.add(logical_id) + drop_entry(self.template, "Parameters", BOOTSTRAP_PARAMETER) + drop_entry(self.template, "Rules", BOOTSTRAP_RULE) + self.notes.append( + "CDK template: CDK metadata and the bootstrap version check were left out; resource " + "names come from the construct paths" + ) + + def replace_custom_resource(self, logical_id: str, resource: dict[str, Any]) -> None: + """A custom resource the CDK adds for a feature Terraform has built in: remove it + and its provider function and role, and keep the feature another way.""" + kind = resource.get("Type") + props = resource.get("Properties") or {} + provider = get_att_target(resource, "ServiceToken") + self.removed.add(logical_id) + if provider: + self.removed.add(provider) + role = get_att_target(self.resources.get(provider, {}), "Role") + if role: + self.removed.add(role) + if kind == AUTO_DELETE: + bucket = props.get("BucketName") + bucket_id = bucket.get("Ref") if isinstance(bucket, dict) else None + if isinstance(bucket_id, str) and bucket_id in self.resources: + self.hints.setdefault(bucket_id, {})["force_destroy"] = True + drop_tag(self.resources[bucket_id], AUTO_DELETE_TAG) + self.notes.append( + f"{logical_id} (CDK autoDeleteObjects) became force_destroy = true on the bucket" + ) + elif kind == LOG_RETENTION: + group = props.get("LogGroupName") + replacement = {"LogGroupName": group, "RetentionInDays": props.get("RetentionInDays")} + self.resources[logical_id] = { + "Type": "AWS::Logs::LogGroup", + "Properties": replacement, + "Metadata": resource.get("Metadata") or {}, + } + self.removed.discard(logical_id) + self.notes.append( + f"{logical_id} (CDK logRetention) became a log group with that retention; import " + "the existing log group or Terraform will fail to create it" + ) + else: + self.notes.append( + f"{logical_id} (CDK restrictDefaultSecurityGroup) was left out: add an " + "aws_default_security_group for the VPC with no rules to get the same effect" + ) + + def remove_unused(self) -> None: + """Remove what was marked, except a provider role or function another resource + still uses. References from bucket policies and DependsOn do not count: + clean_references removes those.""" + still_used: set[str] = set() + for logical_id, resource in self.resources.items(): + if logical_id in self.removed or resource.get("Type") == "AWS::S3::BucketPolicy": + continue + stripped = {k: v for k, v in resource.items() if k not in ("DependsOn", "Metadata")} + still_used |= referenced_ids(stripped) + self.removed = { + logical_id + for logical_id in self.removed + if logical_id not in still_used + or self.resources[logical_id].get("Type") == METADATA_TYPE + } + for logical_id in self.removed: + self.resources.pop(logical_id, None) + clean_references(self.template, self.removed) + + def name_resources(self) -> None: + """Terraform names from the construct paths, and code_path hints for assets.""" + for logical_id, resource in self.resources.items(): + metadata = resource.get("Metadata") + if not isinstance(metadata, dict): + continue + path = metadata.get("aws:cdk:path") + if isinstance(path, str): + name = path_name(path) + if name: + self.names[logical_id] = name + asset = metadata.get("aws:asset:path") + prop = metadata.get("aws:asset:property") + if isinstance(asset, str) and prop in ("Code", "Content"): + self.hints.setdefault(logical_id, {})["code_path"] = f"cdk.out/{asset}" + (resource.get("Properties") or {}).pop(prop, None) + if any("code_path" in h for h in self.hints.values()): + self.notes.append( + "CDK assets: Lambda code is read from cdk.out/asset.*; run `cdk synth` and keep " + "cdk.out next to the Terraform files" + ) + + +def prepare_cdk( + template: dict[str, Any], notes: list[str] +) -> tuple[dict[str, Any], dict[str, str], dict[str, dict[str, Any]]]: + """Returns (template, wanted Terraform names by logical id, converter hints).""" + return CdkTemplate(template, notes).prepare() diff --git a/services/converter-api/converters/cfn/cdk_constants.py b/services/converter-api/converters/cfn/cdk_constants.py new file mode 100644 index 0000000..9686d8e --- /dev/null +++ b/services/converter-api/converters/cfn/cdk_constants.py @@ -0,0 +1,21 @@ +"""Names the CDK writes into synthesized templates.""" + +from __future__ import annotations + +import re + +# Helper Lambda functions the CDK adds to implement a feature through a custom resource, +# recognised by their resource type, and what replaces them in Terraform. +AUTO_DELETE = "Custom::S3AutoDeleteObjects" +LOG_RETENTION = "Custom::LogRetention" +RESTRICT_DEFAULT_SG = "Custom::VpcRestrictDefaultSG" +HANDLED = (AUTO_DELETE, LOG_RETENTION, RESTRICT_DEFAULT_SG) +BOOTSTRAP_PARAMETER = "BootstrapVersion" +BOOTSTRAP_RULE = "CheckBootstrapVersion" +METADATA_TYPE = "AWS::CDK::Metadata" +METADATA_CONDITION = "CDKMetadataAvailable" +AUTO_DELETE_TAG = "aws-cdk:auto-delete-objects" +# Construct path parts the CDK adds below the construct a user names. +PATH_SUFFIXES = ("Resource", "Default") +NON_WORD = re.compile(r"[^A-Za-z0-9]+") +SUB_NAME = re.compile(r"\$\{([A-Za-z0-9.]+)\}") diff --git a/services/converter-api/converters/cfn/constants.py b/services/converter-api/converters/cfn/constants.py new file mode 100644 index 0000000..7b46bc8 --- /dev/null +++ b/services/converter-api/converters/cfn/constants.py @@ -0,0 +1,49 @@ +"""Limits, names and versions the converter uses.""" + +from __future__ import annotations + +# CloudFormation accepts up to 1 MB from S3. 500,000 characters covers large CDK stacks and +# keeps one request well under a second of CPU. +MAX_TEMPLATE_CHARS = 500_000 +MAX_NODES = 100_000 +MAX_DEPTH = 100 +# Nested Fn::If and Fn::Join chains deeper than this are beyond anything written by hand. +MAX_EXPRESSION_DEPTH = 50 +MAX_JSON_DEPTH = 100 +# CloudFormation's own limit on the number of CIDR blocks Fn::Cidr returns. +MAX_CIDR_COUNT = 256 + +SAM_TRANSFORM = "AWS::Serverless-2016-10-31" +LANGUAGE_EXTENSIONS = "AWS::LanguageExtensions" + +PROVIDERS = ("aws", "awscc") +LAYOUTS = ("files", "single") +SOURCES = ("cloudformation", "sam", "cdk") + +TERRAFORM_VERSION = ">= 1.5" +# 6.40 or later: DynamoDB global indexes use key_schema blocks, added in 6.30. +AWS_VERSION = "~> 6.40" +AWSCC_VERSION = "~> 1.0" +ARCHIVE_VERSION = "~> 2.0" + +# Pseudo parameters read from a data source: (data source type, name, attribute). +PSEUDO_DATA = { + "AWS::Region": ("aws_region", "current", "region"), + "AWS::AccountId": ("aws_caller_identity", "current", "account_id"), + "AWS::Partition": ("aws_partition", "current", "partition"), + "AWS::URLSuffix": ("aws_partition", "current", "dns_suffix"), +} + +# Intrinsic functions whose result is text, so a JSON document property holding one is +# already JSON. +STRING_FUNCTIONS = frozenset( + { + "Ref", + "Fn::Sub", + "Fn::Join", + "Fn::GetAtt", + "Fn::ImportValue", + "Fn::ToJsonString", + "Fn::Base64", + } +) diff --git a/services/converter-api/converters/cfn/context.py b/services/converter-api/converters/cfn/context.py new file mode 100644 index 0000000..bbfb1ec --- /dev/null +++ b/services/converter-api/converters/cfn/context.py @@ -0,0 +1,174 @@ +"""The state of one template's conversion: names, notes, the data sources and variables +that references create, and where every parameter, condition, mapping and resource goes. +Context also resolves the names expressions refer to (see ExpressionConverter).""" + +from __future__ import annotations + +import re +from typing import Any + +from converters.cfn.constants import PSEUDO_DATA +from converters.cfn.errors import CfnError +from converters.cfn.expressions import ExpressionConverter +from converters.cfn.models import Attr, Block, ParamInfo, Raw, ResourceInfo +from converters.cfn.naming import UniqueNames, identifier, snake + +ATTRIBUTE = re.compile(r"^[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)*$") + + +class Context(ExpressionConverter): + """Everything the conversion of one template accumulates.""" + + def __init__(self, template: dict[str, Any], provider: str = "aws") -> None: + """Empty state for converting `template` with `provider`.""" + super().__init__() + self.template = template + self.provider = provider + self.notes: list[str] = [] + self.note_set: set[str] = set() + self.params: dict[str, ParamInfo] = {} + self.resources: dict[str, ResourceInfo] = {} + self.conditions: dict[str, str] = {} # CloudFormation condition name -> local name + self.mappings: dict[str, str] = {} # CloudFormation mapping name -> local name + self.data_sources: dict[tuple[str, str], Block] = {} + self.extra_variables: dict[str, Block] = {} + self.variable_names = UniqueNames() + self.local_names = UniqueNames() + self.output_names = UniqueNames() + # Terraform names per resource or data source type, so the extra resources a + # converter adds never collide with each other or with converted resources. + self.type_names: dict[str, UniqueNames] = {} + # Always there for AWS::StackName, so no parameter takes the name. + self.variable_names.reserve("stack_name") + self.stack_name_used = False + self.parameter_types = { + name: str(spec.get("Type")) + for name, spec in (template.get("Parameters") or {}).items() + if isinstance(spec, dict) + } + + def note(self, message: str) -> None: + """Record something the user must look at. Duplicates are dropped.""" + if message not in self.note_set: + self.note_set.add(message) + self.notes.append(message) + + def names_for(self, kind: str) -> UniqueNames: + """The pool of names for one resource or data source type.""" + return self.type_names.setdefault(kind, UniqueNames()) + + def data(self, kind: str, name: str, body: list[Any] | None = None) -> str: + """Register `data "" ""` once and return its address.""" + if (kind, name) not in self.data_sources: + self.data_sources[(kind, name)] = Block("data", [kind, name], body or []) + return f"data.{kind}.{name}" + + def placeholder_variable(self, wanted: str, description: str) -> str: + """A variable standing in for a value Terraform has no way to compute (another + stack's export, an attribute of a resource that was not converted). Returns + `var.`.""" + entry = f"{wanted}\0{description}" + if entry not in self.extra_variables: + name = self.variable_names.take(identifier(wanted)) + self.extra_variables[entry] = Block( + "variable", + [name], + [Attr("description", description), Attr("type", Raw("string"))], + ) + return f"var.{self.extra_variables[entry].labels[0]}" + + def parameter_type(self, name: str) -> str: + """The CloudFormation type of a parameter, or "".""" + return self.parameter_types.get(name, "") + + def mapping_local(self, name: Any) -> str: + """`local.` for a mapping of the template.""" + if not isinstance(name, str) or name not in self.mappings: + raise CfnError(f"'Fn::FindInMap' refers to unknown mapping '{name}'") + return f"local.{self.mappings[name]}" + + def condition(self, name: Any) -> str: + """`local.` for a condition of the template.""" + if not isinstance(name, str) or name not in self.conditions: + raise CfnError(f"Unknown condition '{name}'") + return f"local.{self.conditions[name]}" + + def ref(self, name: Any) -> Any: + """The value of `Ref name`: a variable, a pseudo parameter or a resource.""" + if not isinstance(name, str): + raise CfnError("'Ref' takes the name of a parameter or resource") + if name == "AWS::NoValue": + return None + if name in PSEUDO_DATA: + kind, label, attribute = PSEUDO_DATA[name] + return Raw(f"{self.data(kind, label)}.{attribute}") + if name == "AWS::StackName": + self.stack_name_used = True + return Raw("var.stack_name") + if name == "AWS::StackId": + self.stack_name_used = True + self.note( + "AWS::StackId has no Terraform equivalent; the stack name (var.stack_name) " + "takes its place" + ) + return Raw("var.stack_name") + if name == "AWS::NotificationARNs": + self.note("AWS::NotificationARNs has no Terraform equivalent and became []") + return [] + if name in self.params: + return Raw(self.param_expression(name)) + if name in self.resources: + info = self.resources[name] + if info.kind == "unsupported": + return Raw(self.unresolved(info, "Ref", "the value of Ref")) + return Raw(info.expression(info.ref)) + raise CfnError(f"'Ref' refers to '{name}', which is no parameter or resource") + + def param_expression(self, name: str) -> str: + """The expression for a parameter: its variable, or the SSM value it names.""" + info = self.params[name] + if info.ssm is not None: + value = f"data.aws_ssm_parameter.{info.ssm}.insecure_value" + if info.tf_type.startswith("list("): + return f'split(",", {value})' + return value + return f"var.{info.name}" + + def get_att(self, args: Any) -> Any: + """The value of `Fn::GetAtt [resource, attribute]`.""" + if isinstance(args, str): + resource, _, attribute = args.partition(".") + args = [resource, attribute] + if not isinstance(args, list) or len(args) != 2: + raise CfnError("'Fn::GetAtt' takes [resource, attribute]") + logical_id, attribute = args + if not isinstance(logical_id, str) or logical_id not in self.resources: + raise CfnError(f"'Fn::GetAtt' refers to unknown resource '{logical_id}'") + if not isinstance(attribute, str): + # An attribute name chosen at deploy time (e.g. !GetAtt [R, !Ref Param]). + self.note( + f"Fn::GetAtt on '{logical_id}' with a computed attribute name was not converted" + ) + return None + info = self.resources[logical_id] + if info.kind == "unsupported": + return Raw(self.unresolved(info, attribute, f"the '{attribute}' attribute")) + if attribute in info.attrs: + return Raw(info.expression(info.attrs[attribute])) + if not ATTRIBUTE.match(attribute): + raise CfnError(f"'Fn::GetAtt' attribute '{attribute}' of '{logical_id}' is invalid") + tf_attribute = ".".join(snake(part) for part in attribute.split(".")) + if info.kind == "aws": + self.note( + f"'{logical_id}.{attribute}' became '{info.address}.{tf_attribute}'; check that " + "attribute exists" + ) + return Raw(info.expression(tf_attribute)) + + def unresolved(self, info: ResourceInfo, attribute: str, what: str) -> str: + """A placeholder variable for an attribute of a resource that was not converted.""" + wanted = f"{info.logical_id}_{attribute}" if attribute != "Ref" else info.logical_id + return self.placeholder_variable( + wanted, + f"{what} of {info.logical_id} ({info.cfn_type}), which was not converted", + ) diff --git a/services/converter-api/converters/cfn/convert.py b/services/converter-api/converters/cfn/convert.py new file mode 100644 index 0000000..714c3e6 --- /dev/null +++ b/services/converter-api/converters/cfn/convert.py @@ -0,0 +1,543 @@ +"""CloudFormation template (already expanded from SAM, cleaned up from CDK) to Terraform files.""" + +from __future__ import annotations + +import re +from typing import Any + +from converters.cfn import hcl +from converters.cfn.awscc import AwsccConverter, awscc_type +from converters.cfn.builder import Builder, snippet +from converters.cfn.constants import ( + ARCHIVE_VERSION, + AWS_VERSION, + AWSCC_VERSION, + LAYOUTS, + PROVIDERS, + TERRAFORM_VERSION, +) +from converters.cfn.context import Context +from converters.cfn.errors import CfnError +from converters.cfn.models import BLANK, Attr, Block, Comment, ParamInfo, Raw, ResourceInfo +from converters.cfn.naming import UniqueNames, identifier +from converters.cfn.resources.registry import REGISTRY + +SSM_TYPE = re.compile(r"^AWS::SSM::Parameter::Value<(.+)>$") +LIST_TYPE = re.compile(r"^List<(.+)>$") + + +def variable_type(cfn_type: str) -> str: + """The Terraform type of a CloudFormation parameter type.""" + inner = SSM_TYPE.match(cfn_type) + if inner: + cfn_type = inner.group(1) + if cfn_type == "Number": + return "number" + if cfn_type == "List": + return "list(number)" + if cfn_type == "CommaDelimitedList" or LIST_TYPE.match(cfn_type): + return "list(string)" + return "string" + + +def parameter_default(value: Any, tf_type: str) -> Any: + """A parameter default as a value of the variable's Terraform type.""" + if tf_type == "number": + try: + number = float(value) + except (TypeError, ValueError): + return value + return int(number) if number.is_integer() else number + if tf_type.startswith("list("): + items = value if isinstance(value, list) else str(value).split(",") + items = [str(item).strip() for item in items if str(item).strip() != ""] + if tf_type == "list(number)": + return [parameter_default(item, "number") for item in items] + return items + if isinstance(value, bool): + return "true" if value else "false" + return str(value) if value is not None else None + + +def sentence(text: str) -> str: + """'pick dev or prod' -> 'Pick dev or prod.'""" + text = text.strip() + text = text[:1].upper() + text[1:] + return text if text.endswith((".", "?", "!")) else text + "." + + +class Converter: + """A CloudFormation template (expanded from SAM, cleaned up from CDK) to Terraform + files: parameters, mappings, conditions, resources, outputs and imports.""" + + def __init__( + self, + template: dict[str, Any], + provider: str = "aws", + stack_name: str | None = None, + include_imports: bool = False, + names: dict[str, str] | None = None, + hints: dict[str, dict[str, Any]] | None = None, + ) -> None: + """Convert `template` with `provider`. `names` are wanted Terraform names by logical + id (from the CDK step) and `hints` facts for converters by logical id.""" + if provider not in PROVIDERS: + raise CfnError(f"Unknown provider '{provider}'. Use one of: {', '.join(PROVIDERS)}") + self.template = template + self.ctx = Context(template, provider) + self.stack_name = stack_name + self.include_imports = include_imports + self.wanted_names = names or {} + self.hints = hints or {} + self.variables: list[Block] = [] + self.locals: list[Any] = [] + self.resources: list[Block | Comment] = [] + self.outputs: list[Block] = [] + self.imports: list[Block] = [] + self.sensitive: set[str] = set() + self.sensitive_locals: set[str] = set() + self.report: list[dict[str, Any]] = [] + self.uses_archive = False + + # --- parameters ------------------------------------------------------------------- + + def parameters(self) -> None: + """Parameters as variables, with validation blocks.""" + labels = self._parameter_labels() + for cfn_name, spec in (self.template.get("Parameters") or {}).items(): + name = self.ctx.variable_names.take(identifier(cfn_name)) + cfn_type = str(spec["Type"]) + tf_type = variable_type(cfn_type) + ssm = SSM_TYPE.match(cfn_type) + info = ParamInfo(name, cfn_type, tf_type, ssm=name if ssm else None) + self.ctx.params[cfn_name] = info + + body: list[Any] = [] + description = spec.get("Description") or labels.get(cfn_name) + if ssm: + description = ( + f"{description + ' ' if description else ''}" + f"(name of the SSM parameter that holds the value)" + ).strip() + if description: + body.append(Attr("description", str(description))) + body.append(Attr("type", Raw("string" if ssm else tf_type))) + if "Default" in spec: + body.append( + Attr( + "default", parameter_default(spec["Default"], "string" if ssm else tf_type) + ) + ) + if str(spec.get("NoEcho", "")).lower() == "true": + body.append(Attr("sensitive", True)) + self.sensitive.add(name) + if not ssm: + validations = self._validations(name, spec, tf_type) + if validations: + body.append(BLANK) + body.extend(validations) + self.variables.append(Block("variable", [name], body)) + if ssm: + self.ctx.data("aws_ssm_parameter", name, [Attr("name", Raw(f"var.{name}"))]) + + def _parameter_labels(self) -> dict[str, str]: + """Parameter labels from AWS::CloudFormation::Interface, for descriptions.""" + metadata = self.template.get("Metadata") or {} + interface = ( + metadata.get("AWS::CloudFormation::Interface") if isinstance(metadata, dict) else None + ) + labels = interface.get("ParameterLabels") if isinstance(interface, dict) else None + if not isinstance(labels, dict): + return {} + return { + str(k): str(v.get("default")) + for k, v in labels.items() + if isinstance(v, dict) and v.get("default") + } + + def _validations(self, name: str, spec: dict[str, Any], tf_type: str) -> list[Block]: + """Validation blocks from AllowedValues, AllowedPattern and the length and value limits.""" + ref = f"var.{name}" + rules: list[tuple[str, str]] = [] + constraint = spec.get("ConstraintDescription") + allowed = spec.get("AllowedValues") + if isinstance(allowed, list) and allowed and not tf_type.startswith("list("): + values = [parameter_default(v, tf_type) for v in allowed] + rules.append( + ( + f"contains({hcl.inline(values)}, {ref})", + f"Must be one of: {', '.join(str(v) for v in values)}.", + ) + ) + if tf_type == "string": + if spec.get("AllowedPattern"): + pattern = str(spec["AllowedPattern"]) + rules.append( + ( + f"can(regex({hcl.quote('^(?:' + pattern + ')$')}, {ref}))", + f"Must match the pattern {pattern}.", + ) + ) + for key, operator, words in ( + ("MinLength", ">=", "at least"), + ("MaxLength", "<=", "at most"), + ): + if spec.get(key) is not None: + limit = parameter_default(spec[key], "number") + rules.append( + ( + f"length({ref}) {operator} {limit}", + f"Must be {words} {limit} characters.", + ) + ) + if tf_type == "number": + for key, operator, words in ( + ("MinValue", ">=", "at least"), + ("MaxValue", "<=", "at most"), + ): + if spec.get(key) is not None: + limit = parameter_default(spec[key], "number") + rules.append((f"{ref} {operator} {limit}", f"Must be {words} {limit}.")) + blocks = [] + for condition, message in rules: + text = sentence(str(constraint)) if constraint else message + blocks.append( + Block( + "validation", + [], + [Attr("condition", Raw(condition)), Attr("error_message", text)], + ) + ) + return blocks + + # --- mappings and conditions -------------------------------------------------------- + + def mappings_and_conditions(self) -> None: + """Mappings and conditions as local values.""" + for name, mapping in (self.template.get("Mappings") or {}).items(): + local = self.ctx.local_names.take(identifier(name)) + self.ctx.mappings[str(name)] = local + self.locals.append(Attr(local, self.ctx.expr(mapping))) + conditions = self.template.get("Conditions") or {} + for name in conditions: + self.ctx.conditions[str(name)] = self.ctx.local_names.take(identifier(name)) + rendered: dict[str, str] = {} + for name, condition in conditions.items(): + value = self.ctx.expr(condition) + rendered[self.ctx.conditions[str(name)]] = hcl.render(value) + self.locals.append(Attr(self.ctx.conditions[str(name)], value)) + # A condition built from a NoEcho parameter is sensitive too, and so is anything + # (an output with that Condition) that uses it. + changed = True + while changed: + changed = False + for local, text in rendered.items(): + if local not in self.sensitive_locals and self._uses_sensitive(text): + self.sensitive_locals.add(local) + changed = True + + # --- resources -------------------------------------------------------------------- + + def register(self) -> None: + """Decide every resource's Terraform type and name before converting any, so + references can be resolved in any order.""" + names = UniqueNames() + for logical_id, resource in self.template["Resources"].items(): + cfn_type = resource["Type"] + wanted = identifier(self.wanted_names.get(logical_id) or logical_id) + converter = REGISTRY.get(cfn_type) if self.ctx.provider == "aws" else None + if converter is not None: + info = ResourceInfo( + logical_id, + cfn_type, + converter.tf_type, + names.take(wanted), + ref=converter.ref, + attrs=dict(converter.attrs), + kind="aws", + ) + info.conditional = bool(resource.get("Condition")) + converter.prepare(info, resource) + elif (tf_type := awscc_type(cfn_type)) is not None: + info = ResourceInfo(logical_id, cfn_type, tf_type, names.take(wanted), kind="awscc") + else: + info = ResourceInfo(logical_id, cfn_type, "", wanted, kind="unsupported") + # A prepare hook may have made the resource counted for its own reasons. + info.conditional = info.conditional or bool(resource.get("Condition")) + if info.tf_type: + self.ctx.names_for(info.tf_type).reserve(info.name) + self.ctx.resources[logical_id] = info + + def convert_resources(self) -> None: + """Every resource, with its hand-written converter or with awscc.""" + awscc_types: set[str] = set() + for logical_id, resource in self.template["Resources"].items(): + info = self.ctx.resources[logical_id] + entry = { + "logical_id": logical_id, + "type": info.cfn_type, + "address": None, + "status": info.kind, + } + self.report.append(entry) + if info.kind == "unsupported": + self._unsupported(info, resource) + continue + builder = Builder(self.ctx, info, resource, hints=self.hints.get(logical_id, {})) + converter = REGISTRY.get(info.cfn_type) if info.kind == "aws" else None + if converter is not None: + converter.convert(builder) + else: + awscc_types.add(info.cfn_type) + AwsccConverter(builder).convert() + builder.props.finish() + block = self._resource_block(builder, resource) + entry["address"] = info.address + self.resources.append(block) + self.resources.extend(builder.extra) + if builder.hints.get("archive"): + self.uses_archive = True + if self.include_imports: + self._import(info, resource) + for cfn_type in sorted(awscc_types): + reason = ( + "the awscc provider was requested" + if self.ctx.provider == "awscc" + else "it has no hand-written aws mapping yet" + ) + self.ctx.note( + f"{cfn_type} uses the awscc provider ({reason}): awscc mirrors the " + f"CloudFormation schema, so check {awscc_type(cfn_type)} in the awscc docs" + ) + + def _resource_block(self, builder: Builder, resource: dict[str, Any]) -> Block: + """The main resource block, with count, depends_on and lifecycle.""" + info = builder.info + body: list[Any] = builder.main_count_items() + builder.props.items + meta: list[Any] = [] + depends = resource.get("DependsOn") + if depends: + targets = depends if isinstance(depends, list) else [depends] + addresses = [] + for target in targets: + other = self.ctx.resources.get(str(target)) + if other is None: + raise CfnError(f"'{info.logical_id}' DependsOn unknown resource '{target}'") + if other.kind != "unsupported": + addresses.append(Raw(other.address)) + if addresses: + meta.append(Attr("depends_on", addresses)) + lifecycle = list(builder.lifecycle) + policy = resource.get("DeletionPolicy") + if policy in ("Retain", "RetainExceptOnCreate"): + lifecycle.append(Attr("prevent_destroy", True)) + self.ctx.note( + f"{info.logical_id} has DeletionPolicy {policy}: it became prevent_destroy, so " + "`terraform destroy` fails where CloudFormation leaves the resource behind; use " + "a `removed` block with `destroy = false` to let go of it" + ) + elif policy == "Snapshot" and info.cfn_type not in ( + "AWS::RDS::DBInstance", + "AWS::RDS::DBCluster", + ): + self.ctx.note( + f"{info.logical_id} has DeletionPolicy Snapshot: Terraform takes no snapshot " + "on destroy; take one by hand first" + ) + # prevent_destroy also blocks replacement, so a Retain update policy is covered. + if resource.get("UpdateReplacePolicy") == "Snapshot" or ( + resource.get("UpdateReplacePolicy") == "Retain" + and policy not in ("Retain", "RetainExceptOnCreate") + ): + self.ctx.note( + f"{info.logical_id} has UpdateReplacePolicy " + f"{resource['UpdateReplacePolicy']}: Terraform has no equivalent" + ) + for attribute in ("CreationPolicy", "UpdatePolicy"): + if resource.get(attribute): + self.ctx.note( + f"{info.logical_id} has a {attribute}, which only CloudFormation applies; " + "it was not converted" + ) + metadata = resource.get("Metadata") + if isinstance(metadata, dict) and "AWS::CloudFormation::Init" in metadata: + self.ctx.note( + f"{info.logical_id} uses AWS::CloudFormation::Init (cfn-init), which runs " + "inside CloudFormation only; move it into user_data (cloud-init) or an AMI" + ) + if lifecycle: + meta.append(Block("lifecycle", [], lifecycle)) + if meta: + body = body + ([BLANK] if body else []) + meta + return Block("resource", [info.tf_type, info.name], body) + + def _unsupported(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """A resource without a Terraform resource: a note and a comment.""" + if info.cfn_type.startswith("Custom::") or info.cfn_type == ( + "AWS::CloudFormation::CustomResource" + ): + why = "custom resources run a Lambda function or SNS topic during stack operations" + elif info.cfn_type.startswith("AWS::CloudFormation::"): + why = "it exists inside CloudFormation only" + else: + why = "the aws mappings and the awscc provider both lack this type" + self.ctx.note(f"{info.logical_id} ({info.cfn_type}) was not converted: {why}") + self.resources.append( + Comment( + f"{info.logical_id} ({info.cfn_type}) was not converted, see the notes.\n" + f"Properties: {snippet(resource.get('Properties') or {})}" + ) + ) + + def _import(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """An import block for the resource.""" + converter = REGISTRY.get(info.cfn_type) if info.kind == "aws" else None + identifier_value: Any = None + if converter is not None and converter.import_id: + value = (resource.get("Properties") or {}).get(converter.import_id) + if isinstance(value, str): + identifier_value = value + target = f"{info.address}[0]" if info.conditional else info.address + body = [ + Attr("to", Raw(target)), + Attr("id", identifier_value or f"TODO: physical ID of {info.logical_id}"), + ] + self.imports.append(Block("import", [], body)) + + def _uses_sensitive(self, text: str) -> bool: + """Whether an expression reads a NoEcho parameter or a condition built from one.""" + return any(re.search(rf"\bvar\.{name}\b", text) for name in self.sensitive) or any( + re.search(rf"\blocal\.{name}\b", text) for name in self.sensitive_locals + ) + + # --- outputs ---------------------------------------------------------------------- + + def convert_outputs(self) -> None: + """Outputs, with notes for exports.""" + for name, output in (self.template.get("Outputs") or {}).items(): + tf_name = self.ctx.output_names.take(identifier(name)) + value = self.ctx.expr(output["Value"]) + condition = output.get("Condition") + if condition: + value = Raw(f"{self.ctx.condition(condition)} ? {hcl.inline(value)} : null") + body: list[Any] = [] + if output.get("Description"): + body.append(Attr("description", str(output["Description"]))) + body.append(Attr("value", value)) + if self._uses_sensitive(hcl.render(value)): + body.append(Attr("sensitive", True)) + export = output.get("Export") + if isinstance(export, dict) and "Name" in export: + export_name = self.ctx.expr(export["Name"]) + shown = export_name if isinstance(export_name, str) else hcl.inline(export_name) + if shown.startswith('"') and shown.endswith('"'): + shown = shown[1:-1] + self.ctx.note( + f"Output {name} was exported as '{shown}': Terraform has no exports; other " + "configurations can read it with terraform_remote_state" + ) + self.outputs.append(Block("output", [tf_name], body)) + + # --- files ------------------------------------------------------------------------ + + def _versions(self) -> list[Block | Comment]: + """The terraform block and the provider blocks for the providers in use.""" + uses_aws = any(t.startswith("aws_") for t in self._used_types()) or bool( + self.ctx.data_sources + ) + uses_awscc = any(t.startswith("awscc_") for t in self._used_types()) + providers: dict[str, Any] = {} + if uses_aws or not uses_awscc: + providers["aws"] = {"source": "hashicorp/aws", "version": AWS_VERSION} + if uses_awscc: + providers["awscc"] = {"source": "hashicorp/awscc", "version": AWSCC_VERSION} + if self.uses_archive: + providers["archive"] = {"source": "hashicorp/archive", "version": ARCHIVE_VERSION} + terraform = Block( + "terraform", + [], + [ + Attr("required_version", TERRAFORM_VERSION), + BLANK, + Block("required_providers", [], [Attr(k, v) for k, v in providers.items()]), + ], + ) + blocks: list[Block | Comment] = [terraform] + comment = Comment( + "Region and credentials come from the environment (AWS_REGION, AWS_PROFILE...),\n" + "as with the AWS CLI. Set region here to pin one." + ) + if "aws" in providers: + blocks += [comment, Block("provider", ["aws"], [])] + if uses_awscc: + if "aws" not in providers: + blocks.append(comment) + blocks.append(Block("provider", ["awscc"], [])) + return blocks + + def _used_types(self) -> list[str]: + """Every resource and data source type in use.""" + return [ + block.labels[0] + for block in self.resources + if isinstance(block, Block) and block.type == "resource" + ] + [kind for kind, _ in self.ctx.data_sources] + + def _all_variables(self) -> list[Block]: + """Parameter variables, stack_name when used, and placeholder variables.""" + blocks = list(self.variables) + if self.ctx.stack_name_used: + name = "stack_name" + body: list[Any] = [ + Attr("description", "Name of the stack (replaces AWS::StackName)"), + Attr("type", Raw("string")), + ] + if self.stack_name: + body.append(Attr("default", self.stack_name)) + blocks.insert(0, Block("variable", [name], body)) + blocks.extend(self.ctx.extra_variables.values()) + return blocks + + def files(self, layout: str) -> list[dict[str, str]]: + """The Terraform files, one per kind or a single main.tf.""" + if layout not in LAYOUTS: + raise CfnError(f"Unknown layout '{layout}'. Use one of: {', '.join(LAYOUTS)}") + variables = self._all_variables() + local_block = [Block("locals", [], self.locals)] if self.locals else [] + data = list(self.ctx.data_sources.values()) + main = data + self.resources + import_blocks: list[Block | Comment] = [] + if self.imports: + import_blocks = [ + Comment( + "Adopt the resources the stack created. Replace each TODO with the\n" + "physical ID of the resource:\n" + " aws cloudformation describe-stack-resources --stack-name \n" + "Most types import by that ID; the Import section in the docs of each\n" + "resource type says which ID it takes. Set DeletionPolicy: Retain on every\n" + "resource and delete the stack once `terraform plan` shows no changes." + ) + ] + self.imports + if layout == "single": + blocks = self._versions() + variables + local_block + main + self.outputs + return [{"path": "main.tf", "content": hcl.render_file(blocks + import_blocks)}] + files = [{"path": "versions.tf", "content": hcl.render_file(self._versions())}] + if variables: + files.append({"path": "variables.tf", "content": hcl.render_file(variables)}) + if local_block: + files.append({"path": "locals.tf", "content": hcl.render_file(local_block)}) + files.append({"path": "main.tf", "content": hcl.render_file(main)}) + if self.outputs: + files.append({"path": "outputs.tf", "content": hcl.render_file(self.outputs)}) + if import_blocks: + files.append({"path": "imports.tf", "content": hcl.render_file(import_blocks)}) + return files + + def run(self, layout: str = "files") -> dict[str, Any]: + """Convert the template: files, notes and where each resource went.""" + self.parameters() + self.mappings_and_conditions() + self.register() + self.convert_resources() + self.convert_outputs() + return {"files": self.files(layout), "notes": self.ctx.notes, "resources": self.report} diff --git a/services/converter-api/converters/cfn/errors.py b/services/converter-api/converters/cfn/errors.py new file mode 100644 index 0000000..4c45d41 --- /dev/null +++ b/services/converter-api/converters/cfn/errors.py @@ -0,0 +1,18 @@ +"""The error the converter raises for input it cannot convert.""" + +from __future__ import annotations + + +class CfnError(ValueError): + """Raised when a template cannot be read or converted. + + `message` describes the user's input and is safe to show them. `line` and `column` are + 1-based, set for syntax errors. + """ + + def __init__(self, message: str, line: int | None = None, column: int | None = None) -> None: + """An error about the input, at an optional position.""" + super().__init__(message) + self.message = message + self.line = line + self.column = column diff --git a/services/converter-api/converters/cfn/expressions.py b/services/converter-api/converters/cfn/expressions.py new file mode 100644 index 0000000..30eb8fc --- /dev/null +++ b/services/converter-api/converters/cfn/expressions.py @@ -0,0 +1,515 @@ +"""CloudFormation values and intrinsic functions as Terraform expressions. + +ExpressionConverter turns any CloudFormation value (a literal, a list, a mapping, or an +intrinsic such as `{"Fn::Sub": "..."}`) into an HCL value for hcl.render(). It resolves names +(parameters, resources, conditions, mappings) through methods its subclass, Context, +provides. +""" + +from __future__ import annotations + +import ipaddress +import json +import re +from abc import ABC, abstractmethod +from collections.abc import Callable +from typing import Any + +from converters.cfn import hcl +from converters.cfn.constants import ( + MAX_CIDR_COUNT, + MAX_EXPRESSION_DEPTH, + MAX_JSON_DEPTH, + STRING_FUNCTIONS, +) +from converters.cfn.errors import CfnError +from converters.cfn.models import Attr, Call, Expression, Raw + +NO_VALUE = {"Ref": "AWS::NoValue"} +SUB_VARIABLE = re.compile(r"\$\{([^}]*)\}") +TRAILING_MARKERS = re.compile(r"[$%]+$") +# Operands that need no parentheses: a reference, a number, a quoted string, a call with +# simple arguments, or a negation of one of those. +SIMPLE_EXPRESSION = re.compile( + r'^!?(?:[A-Za-z_][A-Za-z0-9_.\[\]"*-]*|-?[0-9.]+|"(?:[^"\\]|\\.)*"' + r"|[A-Za-z_][A-Za-z0-9_]*\([^()]*\))$" +) +LOGICAL_OPERATORS = {"Fn::And": "&&", "Fn::Or": "||"} + + +def intrinsic_name(value: dict[str, Any]) -> str | None: + """The function name when `value` is an intrinsic function call, else None.""" + if len(value) != 1: + return None + (name,) = value + if name == "Ref" or (isinstance(name, str) and name.startswith("Fn::")): + return name + if name == "Condition" and isinstance(value[name], str): + return name + return None + + +def wrap_operand(text: str) -> str: + """Parentheses around a compound expression used as an operand of an operator.""" + if SIMPLE_EXPRESSION.match(text): + return text + return f"({text})" + + +def scalar_text(value: Any) -> str: + """A literal as CloudFormation turns it into text: true, 1.5, abc.""" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int | float): + return hcl.render(value) + return str(value) + + +def arguments(args: Any, counts: tuple[int, ...], function: str) -> list[Any]: + """The argument list of an intrinsic, checked to hold one of `counts` values.""" + if not isinstance(args, list) or len(args) not in counts: + expected = " or ".join(str(count) for count in counts) + raise CfnError(f"'{function}' takes a list of {expected} values") + return args + + +def template(pieces: list[Any]) -> Any: + """Literal strings and HCL values as one value: the text itself when every piece is + literal, the value when there is only one, otherwise a template string. + + Literal runs are joined before they are escaped, so text split across pieces ("$" then + "{x}") never forms an interpolation, and a "$" or "%" right before an interpolation is + written as ${"$"}, because "$${" would escape it.""" + merged: list[Any] = [] + for piece in pieces: + if isinstance(piece, str) and merged and isinstance(merged[-1], str): + merged[-1] += piece + elif piece != "": + merged.append(piece) + if not merged: + return "" + if len(merged) == 1: + return merged[0] + out: list[str] = [] + for index, piece in enumerate(merged): + if not isinstance(piece, str): + out.append("${" + hcl.inline(piece) + "}") + continue + markers = TRAILING_MARKERS.search(piece) + if markers and index + 1 < len(merged): + out.append(hcl.template_text(piece[: markers.start()])) + out.append("${" + hcl.quote(markers.group()) + "}") + else: + out.append(hcl.template_text(piece)) + return Raw('"' + "".join(out) + '"') + + +def check_json_depth(value: Any) -> None: + """Reject a JSON document nested deeper than MAX_JSON_DEPTH.""" + stack = [(value, 0)] + while stack: + node, depth = stack.pop() + if depth > MAX_JSON_DEPTH: + raise CfnError("A JSON document in the template is nested too deeply") + if isinstance(node, dict): + stack.extend((item, depth + 1) for item in node.values()) + elif isinstance(node, list): + stack.extend((item, depth + 1) for item in node) + + +class ExpressionConverter(ABC): + """Converts CloudFormation values to HCL values. Name lookups (Ref, Fn::GetAtt, + conditions, mappings) and side effects (notes, data sources, variables) are left to the + subclass: see Context.""" + + def __init__(self) -> None: + """The table of intrinsic functions, and no JSON document in progress.""" + # Above 0 while a JSON document (jsonencode) is being converted. + self.json_depth = 0 + self.functions: dict[str, Callable[[Any, int], Any]] = { + "Ref": self.fn_ref, + "Condition": self.fn_condition, + "Fn::GetAtt": self.fn_get_att, + "Fn::Sub": self.fn_sub, + "Fn::Join": self.fn_join, + "Fn::Select": self.fn_select, + "Fn::Split": self.fn_split, + "Fn::GetAZs": self.fn_get_azs, + "Fn::Base64": self.fn_base64, + "Fn::Cidr": self.fn_cidr, + "Fn::FindInMap": self.fn_find_in_map, + "Fn::If": self.fn_if, + "Fn::Equals": self.fn_equals, + "Fn::And": self.fn_and, + "Fn::Or": self.fn_or, + "Fn::Not": self.fn_not, + "Fn::ImportValue": self.fn_import_value, + "Fn::ToJsonString": self.fn_to_json_string, + "Fn::Length": self.fn_length, + "Fn::Transform": self.fn_transform, + } + + # --- what the subclass provides ----------------------------------------------------- + + @abstractmethod + def note(self, message: str) -> None: + """Record something the user must look at.""" + + @abstractmethod + def data(self, kind: str, name: str, body: list[Any]) -> str: + """Register a data source and return its address.""" + + @abstractmethod + def placeholder_variable(self, wanted: str, description: str) -> str: + """A variable standing in for a value Terraform has no way to compute.""" + + @abstractmethod + def ref(self, name: Any) -> Any: + """The value of `Ref name`.""" + + @abstractmethod + def get_att(self, args: Any) -> Any: + """The value of `Fn::GetAtt args`.""" + + @abstractmethod + def condition(self, name: Any) -> str: + """The expression of a named condition.""" + + @abstractmethod + def mapping_local(self, name: Any) -> str: + """The local value holding a named mapping.""" + + @abstractmethod + def parameter_type(self, name: str) -> str: + """The CloudFormation type of a parameter, or "" when there is no such parameter.""" + + # --- values ------------------------------------------------------------------------- + + def expr(self, value: Any, depth: int = 0) -> Any: + """A CloudFormation value as an HCL value. Mapping keys are kept as written.""" + if depth > MAX_EXPRESSION_DEPTH: + raise CfnError("Template expressions are nested too deeply") + if isinstance(value, Expression): + return Raw(value.text) + if isinstance(value, dict): + function = intrinsic_name(value) + if function is not None: + return self.call(function, value[function], depth + 1) + return self.mapping(value, depth) + if isinstance(value, list): + return self.sequence(value, depth) + return value + + def text(self, value: Any) -> str: + """An expression's source text on one line.""" + return hcl.inline(self.expr(value)) + + def is_no_value(self, value: Any) -> bool: + """Whether `value` is `!Ref AWS::NoValue`.""" + return isinstance(value, dict) and value == NO_VALUE + + def mapping(self, value: dict[Any, Any], depth: int) -> Any: + """A mapping, without the keys CloudFormation removes: those set to AWS::NoValue, + and `!If [Cond, x, !Ref AWS::NoValue]` ones when the condition picks NoValue.""" + fixed: dict[str, Any] = {} + optional: list[str] = [] + for key, item in value.items(): + if self.is_no_value(item): + continue + condition, present = self.optional_item(item) + if condition is None: + fixed[str(key)] = self.expr(item, depth + 1) + else: + entry = hcl.inline({str(key): self.expr(present, depth + 1)}) + optional.append(f"{condition} ? {entry} : {{}}") + if not optional: + return fixed + return Raw(f"merge({', '.join([hcl.inline(fixed)] + optional)})") + + def sequence(self, items: list[Any], depth: int) -> Any: + """A list, without the items CloudFormation removes: `!Ref AWS::NoValue`, and + `!If [Cond, x, !Ref AWS::NoValue]` when the condition picks NoValue.""" + kept = [item for item in items if not self.is_no_value(item)] + converted = [self.expr(item, depth + 1) for item in kept] + if not any(self.optional_item(item)[0] for item in kept): + return converted + return Raw(f"[for item in {hcl.inline(converted)} : item if item != null]") + + def optional_item(self, item: Any) -> tuple[str | None, Any]: + """For `!If [Cond, x, !Ref AWS::NoValue]` (or with the branches swapped): the + condition under which the item exists, and x. Otherwise (None, item).""" + if not (isinstance(item, dict) and intrinsic_name(item) == "Fn::If"): + return None, item + args = item["Fn::If"] + if not isinstance(args, list) or len(args) != 3: + return None, item + name, yes, no = args + if self.is_no_value(no) and not self.is_no_value(yes): + return self.condition(name), yes + if self.is_no_value(yes) and not self.is_no_value(no): + return f"!{self.condition(name)}", no + return None, item + + def json(self, value: Any) -> Any: + """A JSON document property (IAM policy, event pattern, state machine definition) + as `jsonencode({...})`, or the string itself when it is already JSON text.""" + if isinstance(value, str): + try: + value = json.loads(value) + except (ValueError, RecursionError): + return value + check_json_depth(value) + function = intrinsic_name(value) if isinstance(value, dict) else None + if function in STRING_FUNCTIONS: + # Ref, Sub and the like give text, which is already a JSON document. + return self.expr(value) + if function == "Fn::If": + name, yes, no = arguments(value[function], (3,), "Fn::If") + branches = [ + "null" if self.is_no_value(branch) else hcl.inline(self.json(branch)) + for branch in (yes, no) + ] + return Raw(f"{self.condition(name)} ? {branches[0]} : {branches[1]}") + self.json_depth += 1 + try: + return Call("jsonencode", self.expr(value)) + finally: + self.json_depth -= 1 + + def call(self, function: str, args: Any, depth: int) -> Any: + """One intrinsic function.""" + handler = self.functions.get(function) + if handler is None: + self.note(f"Intrinsic function '{function}' is not supported and became null") + return None + return handler(args, depth) + + # --- intrinsic functions ------------------------------------------------------------- + + def fn_ref(self, args: Any, depth: int) -> Any: + """Ref.""" + return self.ref(args) + + def fn_get_att(self, args: Any, depth: int) -> Any: + """Fn::GetAtt.""" + return self.get_att(args) + + def fn_condition(self, args: Any, depth: int) -> Any: + """`Condition: Name` inside Fn::And, Fn::Or and Fn::Not.""" + return Raw(self.condition(args)) + + def fn_sub(self, args: Any, depth: int) -> Any: + """Fn::Sub as a template string.""" + variables: dict[str, Any] = {} + if isinstance(args, list): + if len(args) != 2 or not isinstance(args[1], dict): + raise CfnError("'Fn::Sub' takes a string or [string, {variables}]") + args, variables = args + if not isinstance(args, str): + raise CfnError("'Fn::Sub' needs a string") + pieces: list[Any] = [] + position = 0 + for match in SUB_VARIABLE.finditer(args): + if match.start() > position: + pieces.append(args[position : match.start()]) + name = match.group(1).strip() + position = match.end() + if name.startswith("!"): + pieces.append("${" + name[1:] + "}") + elif name in variables: + pieces.append(self.expr(variables[name], depth + 1)) + elif "." in name and not name.startswith("AWS::"): + resource, _, attribute = name.partition(".") + pieces.append(self.get_att([resource, attribute])) + else: + pieces.append(self.ref(name)) + if position < len(args): + pieces.append(args[position:]) + return template(pieces) + + def fn_join(self, args: Any, depth: int) -> Any: + """Fn::Join: a template string when every item is one value, otherwise join().""" + delimiter, items = arguments(args, (2,), "Fn::Join") + if isinstance(items, list): + # CloudFormation leaves out AWS::NoValue items, and their delimiter with them. + items = [item for item in items if not self.is_no_value(item)] + optional = any(self.optional_item(item)[0] for item in items) + listed = any( + isinstance(item, dict) and intrinsic_name(item) in ("Fn::GetAZs", "Fn::Split") + for item in items + ) + if isinstance(delimiter, str) and not optional and not listed: + pieces: list[Any] = [] + for index, item in enumerate(items): + if index: + pieces.append(delimiter) + if isinstance(item, str | int | float): + pieces.append(scalar_text(item)) + else: + pieces.append(self.expr(item, depth + 1)) + return template(pieces) + return Raw(f"join({hcl.inline(self.expr(delimiter, depth))}, {self.text(items)})") + + def fn_select(self, args: Any, depth: int) -> Any: + """Fn::Select: the item itself for a literal list and index, otherwise element().""" + index, items = arguments(args, (2,), "Fn::Select") + if isinstance(items, list) and isinstance(index, int | str) and str(index).isdigit(): + position = int(index) + if position >= len(items): + raise CfnError(f"'Fn::Select' index {position} is out of range") + return self.expr(items[position], depth) + return Raw(f"element({self.text(items)}, {hcl.inline(self.expr(index, depth))})") + + def fn_split(self, args: Any, depth: int) -> Any: + """Fn::Split: the list itself for literal text, otherwise split().""" + delimiter, source = arguments(args, (2,), "Fn::Split") + if isinstance(delimiter, str) and isinstance(source, str): + return source.split(delimiter) + return Raw(f"split({hcl.inline(self.expr(delimiter, depth))}, {self.text(source)})") + + def fn_get_azs(self, args: Any, depth: int) -> Any: + """Fn::GetAZs: the availability zones of the current region.""" + if args not in ("", None) and args != {"Ref": "AWS::Region"}: + self.note("Fn::GetAZs for another region became the zones of the current region") + address = self.data("aws_availability_zones", "available", [Attr("state", "available")]) + return Raw(f"{address}.names") + + def fn_base64(self, args: Any, depth: int) -> Any: + """Fn::Base64.""" + return Raw(f"base64encode({hcl.inline(self.expr(args, depth))})") + + def fn_cidr(self, args: Any, depth: int) -> Any: + """Fn::Cidr: the blocks themselves for a literal network, otherwise cidrsubnet().""" + block, count, bits = arguments(args, (3,), "Fn::Cidr") + try: + count_value = int(count) + bits_value = int(bits) + except (TypeError, ValueError): + count_value = bits_value = -1 + if count_value > MAX_CIDR_COUNT: + raise CfnError(f"'Fn::Cidr' makes at most {MAX_CIDR_COUNT} blocks") + if isinstance(block, str) and count_value > 0 and bits_value > 0: + return self.literal_cidr(block, count_value, bits_value) + block_text = hcl.inline(self.expr(block, depth)) + count_text = hcl.inline(self.expr(count, depth)) + bits_text = hcl.inline(self.expr(bits, depth)) + size = f'(strcontains({block_text}, ":") ? 128 : 32)' + newbits = f'{size} - {wrap_operand(bits_text)} - tonumber(split("/", {block_text})[1])' + return Raw(f"[for i in range({count_text}) : cidrsubnet({block_text}, {newbits}, i)]") + + def literal_cidr(self, block: str, count: int, bits: int) -> list[str]: + """The first `count` blocks of `block` with `bits` host bits each.""" + try: + network = ipaddress.ip_network(block, strict=False) + subnets: list[str] = [] + for subnet in network.subnets(new_prefix=network.max_prefixlen - bits): + subnets.append(str(subnet)) + if len(subnets) == count: + break + return subnets + except ValueError as exc: + raise CfnError(f"'Fn::Cidr' is unable to split '{block}' that way") from exc + + def fn_find_in_map(self, args: Any, depth: int) -> Any: + """Fn::FindInMap, with lookup() when a DefaultValue is given.""" + args = arguments(args, (3, 4), "Fn::FindInMap") + local = self.mapping_local(args[0]) + first = hcl.inline(self.expr(args[1], depth)) + second = hcl.inline(self.expr(args[2], depth)) + if len(args) == 4: + default = args[3] + if isinstance(default, dict) and "DefaultValue" in default: + default = default["DefaultValue"] + default_text = hcl.inline(self.expr(default, depth)) + return Raw(f"lookup(lookup({local}, {first}, {{}}), {second}, {default_text})") + return Raw(f"{local}[{first}][{second}]") + + def fn_if(self, args: Any, depth: int) -> Any: + """Fn::If as a conditional expression.""" + name, when_true, when_false = arguments(args, (3,), "Fn::If") + condition = self.condition(name) + yes = hcl.inline(self.expr(when_true, depth)) + no = hcl.inline(self.expr(when_false, depth)) + if self.json_depth and not (isinstance(when_true, str) and isinstance(when_false, str)): + # Inside a JSON document the branches may differ in shape (a string or a list of + # them); a conditional needs one type, so each branch is encoded on its own. + return Raw(f"jsondecode({condition} ? jsonencode({yes}) : jsonencode({no}))") + return Raw(f"{condition} ? {yes} : {no}") + + def fn_equals(self, args: Any, depth: int) -> Any: + """Fn::Equals. CloudFormation compares as text, while Terraform treats 2 and "2", or + true and "true", as different: literals become strings and Number parameters go + through tostring().""" + texts = [] + for side in arguments(args, (2,), "Fn::Equals"): + if isinstance(side, bool | int | float): + text = hcl.quote(scalar_text(side)) + else: + text = hcl.inline(self.expr(side, depth)) + if self.is_number_parameter(side): + text = f"tostring({text})" + texts.append(text) + return Raw(f"{wrap_operand(texts[0])} == {wrap_operand(texts[1])}") + + def is_number_parameter(self, value: Any) -> bool: + """Whether `value` is a Ref to a parameter of type Number.""" + return ( + isinstance(value, dict) + and set(value) == {"Ref"} + and self.parameter_type(str(value["Ref"])) == "Number" + ) + + def fn_and(self, args: Any, depth: int) -> Any: + """Fn::And.""" + return self.logical(args, depth, "Fn::And") + + def fn_or(self, args: Any, depth: int) -> Any: + """Fn::Or.""" + return self.logical(args, depth, "Fn::Or") + + def logical(self, args: Any, depth: int, function: str) -> Any: + """Fn::And or Fn::Or: the conditions joined by `&&` or `||`.""" + if not isinstance(args, list) or not 2 <= len(args) <= 10: + raise CfnError(f"'{function}' takes a list of 2 to 10 conditions") + parts = [wrap_operand(hcl.inline(self.expr(arg, depth))) for arg in args] + return Raw(f" {LOGICAL_OPERATORS[function]} ".join(parts)) + + def fn_not(self, args: Any, depth: int) -> Any: + """Fn::Not.""" + (value,) = arguments(args, (1,), "Fn::Not") + return Raw(f"!{wrap_operand(hcl.inline(self.expr(value, depth)))}") + + def fn_import_value(self, args: Any, depth: int) -> Any: + """Fn::ImportValue as a variable: Terraform has no stack exports.""" + if isinstance(args, str): + export = args + else: + rendered = self.expr(args, depth) + export = rendered if isinstance(rendered, str) else hcl.inline(rendered) + variable = self.placeholder_variable( + f"import_{export}", + f"Value of the CloudFormation export '{export}' (Fn::ImportValue)", + ) + self.note( + f"Fn::ImportValue '{export}' became {variable}: Terraform has no stack exports; " + "pass the value in or read it with a terraform_remote_state or data source" + ) + return Raw(variable) + + def fn_to_json_string(self, args: Any, depth: int) -> Any: + """Fn::ToJsonString (AWS::LanguageExtensions).""" + return Call("jsonencode", self.expr(args, depth)) + + def fn_length(self, args: Any, depth: int) -> Any: + """Fn::Length (AWS::LanguageExtensions).""" + if isinstance(args, list): + return len(args) + return Raw(f"length({self.text(args)})") + + def fn_transform(self, args: Any, depth: int) -> Any: + """Fn::Transform runs a macro inside CloudFormation: reported, becomes null.""" + name = args.get("Name") if isinstance(args, dict) else None + self.note( + f"Fn::Transform ({name or 'a macro'}) runs inside CloudFormation and was not converted" + ) + return None diff --git a/services/converter-api/converters/cfn/hcl.py b/services/converter-api/converters/cfn/hcl.py new file mode 100644 index 0000000..95f4e64 --- /dev/null +++ b/services/converter-api/converters/cfn/hcl.py @@ -0,0 +1,216 @@ +"""Renders the HCL syntax tree (converters/cfn/models.py) as text that already matches +`terraform fmt`. + +Values are plain Python data (None, bool, int, float, str, list, dict) plus Raw for an +expression that is already HCL, Call for a function call whose argument is rendered as HCL +and Comment for a comment line inside an object or a body. +""" + +from __future__ import annotations + +import json +import math +import re +from typing import Any + +from converters.cfn.models import BLANK, Attr, Block, Call, Comment, Raw + +INDENT = " " +# A list of plain values stays on one line when it fits in this many characters. +INLINE_WIDTH = 80 +BARE_KEY = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*$") +KEYWORDS = frozenset({"true", "false", "null", "for", "in", "if"}) + + +def quote(text: str) -> str: + """A literal string as an HCL quoted string. `${` and `%{` are escaped so they stay text.""" + escaped = ( + text.replace("\\", "\\\\") + .replace('"', '\\"') + .replace("\n", "\\n") + .replace("\r", "\\r") + .replace("\t", "\\t") + .replace("${", "$${") + .replace("%{", "%%{") + ) + return f'"{escaped}"' + + +def template_text(text: str) -> str: + """Literal text for the inside of a template string: the escapes of quote(), without + the quotes.""" + return quote(text)[1:-1] + + +def key(name: str) -> str: + """An object key: bare when it is a plain identifier, quoted otherwise.""" + if BARE_KEY.match(name) and name not in KEYWORDS: + return name + return quote(name) + + +def object_key(name: Any) -> str: + """An object key, or `(expression)` for a key computed by an expression.""" + if isinstance(name, Raw): + return f"({name.text})" + return key(str(name)) + + +def number(value: int | float) -> str: + """A number as HCL writes it: 3 for 3.0, quoted text for infinity and NaN.""" + if isinstance(value, float): + if not math.isfinite(value): + return quote(str(value)) + if value.is_integer() and abs(value) < 1e16: + return str(int(value)) + return repr(value) + return str(value) + + +def render(value: Any, level: int = 0) -> str: + """Render a value. Lines after the first are indented for nesting depth `level`.""" + if value is None: + return "null" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int | float): + return number(value) + if isinstance(value, str): + return quote(value) + if isinstance(value, Raw): + return value.text + if isinstance(value, Call): + return f"{value.fn}({render(value.arg, level)})" + if isinstance(value, list | tuple): + return render_list(list(value), level) + if isinstance(value, dict): + return render_object(value, level) + # Anything else (dates and the like from YAML) is written as its text. + return quote(json.dumps(value, default=str).strip('"')) + + +def inline(value: Any) -> str: + """Render a value on one line, for use inside a larger expression: a function argument, + a conditional branch, a template interpolation.""" + if isinstance(value, Call): + return f"{value.fn}({inline(value.arg)})" + if isinstance(value, list | tuple): + return "[" + ", ".join(inline(item) for item in value) + "]" + if isinstance(value, dict): + if not value: + return "{}" + parts = [ + f"{object_key(name)} = {inline(item)}" + for name, item in value.items() + if not isinstance(item, Comment) + ] + return "{ " + ", ".join(parts) + " }" + return render(value, 0) + + +def render_list(items: list[Any], level: int) -> str: + """A list on one line when it is short and flat, otherwise one item per line.""" + if not items: + return "[]" + parts = [render(item, level + 1) for item in items] + one_line = "[" + ", ".join(parts) + "]" + flat = all(not isinstance(item, dict | list | tuple) or not item for item in items) + single = all("\n" not in part for part in parts) + if flat and single and len(one_line) + level * 2 <= INLINE_WIDTH: + return one_line + pad = INDENT * (level + 1) + lines = ["["] + [f"{pad}{part}," for part in parts] + [INDENT * level + "]"] + return "\n".join(lines) + + +def render_object(mapping: dict[Any, Any], level: int) -> str: + """An object, one `key = value` per line, aligned like a body.""" + if not mapping: + return "{}" + items: list[Any] = [] + for name, value in mapping.items(): + if isinstance(value, Comment): + items.append(value) + else: + items.append(Attr(object_key(name), value)) + lines = ["{"] + BodyWriter(level + 1).write(items) + [INDENT * level + "}"] + return "\n".join(lines) + + +def render_block(block: Block, level: int = 0) -> str: + """A block with its labels and body.""" + pad = INDENT * level + labels = "".join(f" {quote(label)}" for label in block.labels) + if not block.body: + return f"{pad}{block.type}{labels} {{}}" + body = BodyWriter(level + 1).write(block.body) + return "\n".join([f"{pad}{block.type}{labels} {{"] + body + [f"{pad}}}"]) + + +def render_file(blocks: list[Block | Comment]) -> str: + """Top-level blocks separated by blank lines, ending with a newline. A comment sits + directly above the block that follows it.""" + out = "" + previous_was_comment = False + for block in blocks: + if out: + out += "\n" if previous_was_comment else "\n\n" + if isinstance(block, Comment): + out += "\n".join(f"# {line}".rstrip() for line in block.text.split("\n")) + previous_was_comment = True + else: + out += render_block(block) + previous_was_comment = False + return out + "\n" + + +class BodyWriter: + """Writes the attributes, blocks and comments of one body, with `=` aligned the way + terraform fmt aligns it: consecutive single-line attributes form a group, anything else + ends the group.""" + + def __init__(self, level: int) -> None: + """A body at nesting depth `level`.""" + self.level = level + self.pad = INDENT * level + self.lines: list[str] = [] + self.group: list[tuple[str, str]] = [] + + def write(self, items: list[Any]) -> list[str]: + """The lines of the body.""" + for item in items: + self.add(item) + self.flush() + while self.lines and self.lines[-1] == "": + self.lines.pop() + return self.lines + + def add(self, item: Any) -> None: + """One item of the body.""" + if isinstance(item, Attr): + text = render(item.value, self.level) + if "\n" in text: + self.flush() + self.lines.append(f"{self.pad}{item.name} = {text}") + else: + self.group.append((item.name, text)) + elif isinstance(item, Block): + self.flush() + self.lines.extend(render_block(item, self.level).split("\n")) + elif item is BLANK: + self.flush() + if self.lines and self.lines[-1] != "": + self.lines.append("") + elif isinstance(item, Comment): + self.flush() + self.lines.extend(f"{self.pad}# {line}".rstrip() for line in item.text.split("\n")) + else: + raise TypeError(f"Unexpected body item {item!r}") + + def flush(self) -> None: + """Write the pending group of single-line attributes, aligned on `=`.""" + if not self.group: + return + width = max(len(name) for name, _ in self.group) + self.lines.extend(f"{self.pad}{name.ljust(width)} = {text}" for name, text in self.group) + self.group = [] diff --git a/services/converter-api/converters/cfn/models.py b/services/converter-api/converters/cfn/models.py new file mode 100644 index 0000000..2c32076 --- /dev/null +++ b/services/converter-api/converters/cfn/models.py @@ -0,0 +1,98 @@ +"""The data the converter works with: the HCL syntax tree it writes, and where each +CloudFormation parameter and resource ends up in Terraform.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + + +@dataclass(frozen=True) +class Raw: + """An HCL expression, written exactly as given: `var.name`, `"${var.a}-x"`.""" + + text: str + + +@dataclass(frozen=True) +class Call: + """`fn(arg)`, with `arg` rendered as an HCL value, so it can span several lines.""" + + fn: str + arg: Any + + +@dataclass(frozen=True) +class Comment: + """A `#` comment line in a body or an object.""" + + text: str + + +@dataclass +class Attr: + """`name = value` in a body.""" + + name: str + value: Any + + +@dataclass +class Block: + """`type "label" ... { body }`. The body holds Attr, Block and Comment items.""" + + type: str + labels: list[str] = field(default_factory=list) + body: list[Any] = field(default_factory=list) + + +# A blank line between groups of body items. A comment with this text is never written. +BLANK = Comment("\0blank") + + +@dataclass(frozen=True) +class Expression: + """An HCL expression placed in a template by the SAM or CDK step, such as + `file("${path.module}/api.yaml")`. JSON and YAML have no way to make this type, so only + the converter itself can place one.""" + + text: str + + +@dataclass +class ParamInfo: + """Where a CloudFormation parameter ends up.""" + + name: str # Terraform variable name + cfn_type: str + tf_type: str + ssm: str | None = None # data source name when the value comes from SSM + + +@dataclass +class ResourceInfo: + """Where a CloudFormation resource ends up in Terraform.""" + + logical_id: str + cfn_type: str + tf_type: str # e.g. "aws_s3_bucket"; "" when it has no Terraform resource + name: str # Terraform resource name + ref: str = "id" # attribute that `Ref` returns + attrs: dict[str, str] = field(default_factory=dict) # Fn::GetAtt name -> attribute + kind: str = "aws" # "aws", "awscc" or "unsupported" + conditional: bool = False + # Per-attribute overrides: a whole expression in place of `address.attribute`. + overrides: dict[str, str] = field(default_factory=dict) + + @property + def address(self) -> str: + """`.`, as Terraform addresses the resource.""" + return f"{self.tf_type}.{self.name}" + + def expression(self, attribute: str) -> str: + """The expression that reads `attribute` of the resource, with `[0]` when the + resource has a count.""" + if attribute in self.overrides: + return self.overrides[attribute] + index = "[0]" if self.conditional else "" + return f"{self.address}{index}.{attribute}" diff --git a/services/converter-api/converters/cfn/naming.py b/services/converter-api/converters/cfn/naming.py new file mode 100644 index 0000000..a9f084d --- /dev/null +++ b/services/converter-api/converters/cfn/naming.py @@ -0,0 +1,140 @@ +"""Names: CloudFormation identifiers to Terraform identifiers and attribute names.""" + +from __future__ import annotations + +import re + +# Words that the awscc provider keeps whole instead of splitting at the case change. +_WHOLE_WORDS = ( + ("CloudFormation", "Cloudformation"), + ("CloudFront", "Cloudfront"), + ("CloudWatch", "Cloudwatch"), + ("FSx", "Fsx"), + ("OTel", "Otel"), +) +_S3 = re.compile(r"(^|_)s_3(_|$)") +_EC2 = re.compile(r"(^|_)ec_2(_|$)") +_VERSION = re.compile(r"_v_(\d+)(_|$)") +_IDENTIFIER_INVALID = re.compile(r"[^a-z0-9_]+") +_REPEATED_UNDERSCORES = re.compile(r"_{2,}") + +# Names Terraform reserves inside a variable, resource or output block. +_RESERVED = frozenset( + { + "count", + "depends_on", + "for_each", + "lifecycle", + "locals", + "module", + "provider", + "providers", + "source", + "terraform", + "version", + } +) + + +def _split_words(name: str) -> str: + """CamelCase to snake_case, the way the awscc provider does it. + + Digits are separate words ('Ipv6CidrBlock' -> 'ipv_6_cidr_block') and runs of capitals + are one word ('DBInstanceClass' -> 'db_instance_class'). ASCII only: CloudFormation + names are ASCII, and anything else is replaced by the caller. + """ + out: list[str] = [] + size = len(name) + for i, char in enumerate(name): + is_cap = "A" <= char <= "Z" + is_low = "a" <= char <= "z" + is_num = "0" <= char <= "9" + lower = char.lower() if is_cap else char + if i + 1 < size: + nxt = name[i + 1] + next_cap = "A" <= nxt <= "Z" + next_low = "a" <= nxt <= "z" + next_num = "0" <= nxt <= "9" + if ( + (is_cap and (next_low or next_num)) + or (is_low and (next_cap or next_num)) + or (is_num and (next_cap or next_low)) + ): + if is_cap and next_low and i > 0 and "A" <= name[i - 1] <= "Z": + out.append("_") + out.append(lower) + if is_low or is_num or next_num: + out.append("_") + continue + out.append("_" if char in " _-.:/" else lower) + return "".join(out) + + +def snake(name: str) -> str: + """A CloudFormation property name as an awscc (and mostly aws) attribute name. + + 'BucketName' -> 'bucket_name', 'VPCId' -> 'vpc_id', 'S3Bucket' -> 's3_bucket'. + """ + for word, replacement in _WHOLE_WORDS: + name = name.replace(word, replacement) + result = _split_words(name) + result = _S3.sub(r"\1s3\2", result) + result = _EC2.sub(r"\1ec2\2", result) + return _VERSION.sub(r"_v\1\2", result) + + +def word_breaks(name: str) -> str: + """`_` where a new word starts, in one pass. Unlike snake(), digits stay with their + word: 'S3Endpoint' -> 'S3_Endpoint', 'PublicSubnet1' -> 'Public_Subnet1', + 'DBInstance' -> 'DB_Instance'.""" + out: list[str] = [] + for index, char in enumerate(name): + if index and char.isupper(): + previous = name[index - 1] + following = name[index + 1] if index + 1 < len(name) else "" + if previous.islower() or previous.isdigit(): + out.append("_") + elif previous.isupper() and following.islower(): + out.append("_") + out.append(char) + return "".join(out) + + +def identifier(name: str, fallback: str = "this") -> str: + """A valid Terraform block label from any CloudFormation name. + + 'MyBucket' -> 'my_bucket', '1stQueue' -> 'r_1st_queue'. Never empty, never reserved. + """ + words = _IDENTIFIER_INVALID.sub("_", word_breaks(str(name)).lower()) + words = _REPEATED_UNDERSCORES.sub("_", words).strip("_") + if not words: + words = fallback + if words[0].isdigit(): + words = f"r_{words}" + words = words[:63].rstrip("_") + return f"{words}_" if words in _RESERVED else words + + +class UniqueNames: + """Hands out identifiers, adding _2, _3... when two names collide.""" + + def __init__(self) -> None: + """No names taken yet.""" + self._used: set[str] = set() + # Next suffix to try per wanted name, so many collisions stay linear. + self._next: dict[str, int] = {} + + def take(self, wanted: str) -> str: + """`wanted`, or `wanted_2`, `wanted_3`... when it is taken already.""" + name = wanted + counter = self._next.get(wanted, 2) + while name in self._used: + name = f"{wanted}_{counter}" + counter += 1 + self._next[wanted] = counter + self._used.add(name) + return name + + def reserve(self, name: str) -> None: + """Mark `name` as taken without handing it out.""" + self._used.add(name) diff --git a/services/converter-api/converters/cfn/parse.py b/services/converter-api/converters/cfn/parse.py new file mode 100644 index 0000000..7815365 --- /dev/null +++ b/services/converter-api/converters/cfn/parse.py @@ -0,0 +1,258 @@ +"""Read a CloudFormation, SAM or CDK-synthesized template (JSON or YAML) into a dict. + +YAML short forms (`!Ref X`, `!GetAtt A.B`, `!Sub ...`) become the long JSON forms +(`{"Ref": "X"}`, `{"Fn::GetAtt": ["A", "B"]}`), so the converter only handles one shape. +""" + +from __future__ import annotations + +import json +import math +import re +from typing import Any + +import yaml + +from converters.cfn.constants import ( + MAX_DEPTH, + MAX_NODES, + MAX_TEMPLATE_CHARS, + SAM_TRANSFORM, +) +from converters.cfn.errors import CfnError +from converters.yaml_safety import SafeMergeLoader, check_yaml_limits + +TOP_LEVEL = { + "AWSTemplateFormatVersion", + "Description", + "Metadata", + "Parameters", + "Rules", + "Mappings", + "Conditions", + "Transform", + "Resources", + "Outputs", + "Globals", + "Hooks", +} + +FUNCTIONS = { + "And", + "Base64", + "Cidr", + "Equals", + "FindInMap", + "ForEach", + "GetAtt", + "GetAZs", + "If", + "ImportValue", + "Join", + "Length", + "Not", + "Or", + "Select", + "Split", + "Sub", + "ToJsonString", + "Transform", +} + + +class CfnLoader(SafeMergeLoader): + """Safe YAML loader for CloudFormation: short-form tags, and YAML 1.2 scalars. + + Under YAML 1.1 (PyYAML's default) `2010-09-09` is a date, `on` is True and `0755` is 493. + CloudFormation keeps those as strings, so only true/false, null and plain decimal + numbers are typed here. + """ + + +NULL = re.compile(r"^(?:~|null|Null|NULL|)$") +BOOL = re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$") +INT = re.compile(r"^[-+]?(?:0|[1-9][0-9]*)$") +FLOAT = re.compile(r"^[-+]?(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?$") + +CfnLoader.yaml_implicit_resolvers = {} +for _tag, _pattern, _first in ( + ("tag:yaml.org,2002:null", NULL, ["~", "n", "N", ""]), + ("tag:yaml.org,2002:bool", BOOL, list("tTfF")), + ("tag:yaml.org,2002:int", INT, list("-+0123456789")), + ("tag:yaml.org,2002:float", FLOAT, list("-+.0123456789")), + ("tag:yaml.org,2002:merge", re.compile(r"^(?:<<)$"), ["<"]), +): + CfnLoader.add_implicit_resolver(_tag, _pattern, _first) + + +def construct_bool(loader: yaml.SafeLoader, node: yaml.ScalarNode) -> bool: + """true/false in any case CloudFormation accepts, as a boolean.""" + return loader.construct_scalar(node).lower() == "true" + + +CfnLoader.add_constructor("tag:yaml.org,2002:bool", construct_bool) + + +def construct_tag(loader: yaml.SafeLoader, suffix: str, node: yaml.Node) -> dict[str, Any]: + """`!Name value` -> `{"Fn::Name": value}` (`!Ref` and `!Condition` keep their name).""" + if isinstance(node, yaml.ScalarNode): + value: Any = loader.construct_scalar(node) + elif isinstance(node, yaml.SequenceNode): + value = loader.construct_sequence(node, deep=True) + else: + value = loader.construct_mapping(node, deep=True) + if suffix == "Ref": + return {"Ref": value} + if suffix == "Condition": + return {"Condition": value} + if suffix not in FUNCTIONS: + mark = node.start_mark + raise CfnError(f"Unknown YAML tag '!{suffix}'", mark.line + 1, mark.column + 1) + if suffix == "GetAtt" and isinstance(value, str): + # Short form `!GetAtt Resource.Attribute.With.Dots`: the first dot splits. + resource, _, attribute = value.partition(".") + value = [resource, attribute] + return {f"Fn::{suffix}": value} + + +CfnLoader.add_multi_constructor("!", construct_tag) + + +def syntax_error(exc: yaml.YAMLError) -> CfnError: + """A YAML syntax error as a CfnError with its position.""" + # Only the parser's description of the input reaches the user, never the exception text. + problem = getattr(exc, "problem", None) or "syntax error" + mark = getattr(exc, "problem_mark", None) + line = mark.line + 1 if mark is not None else None + column = mark.column + 1 if mark is not None else None + return CfnError(f"Invalid YAML: {problem}", line, column) + + +# CloudFormation's rule for logical IDs, and for parameter, condition, mapping and output +# names. Enforcing it also keeps every name safe to use in generated HCL. +NAME = re.compile(r"^[A-Za-z0-9]{1,255}$") + + +def check_shape(data: Any) -> None: + """Depth and size limits on loaded data, without recursion. Infinite or NaN numbers + (YAML `.inf`, `1e400`) are rejected: no CloudFormation value is one.""" + stack: list[tuple[Any, int]] = [(data, 0)] + count = 0 + while stack: + node, depth = stack.pop() + count += 1 + if count > MAX_NODES: + raise CfnError(f"Template too large: more than {MAX_NODES:,} values") + if depth > MAX_DEPTH: + raise CfnError("Template nested too deeply") + if isinstance(node, float) and not math.isfinite(node): + raise CfnError(f"Invalid number in template: {node}") + if isinstance(node, dict): + stack.extend((k, depth + 1) for k in node) + stack.extend((v, depth + 1) for v in node.values()) + elif isinstance(node, list): + stack.extend((v, depth + 1) for v in node) + + +def load_template(text: str) -> dict[str, Any]: + """Parse template text (JSON or YAML) and check the parts the converter relies on. + + Raises CfnError with a message for the user. + """ + if not text or not text.strip(): + raise CfnError("Input is empty") + if len(text) > MAX_TEMPLATE_CHARS: + raise CfnError(f"Template is longer than {MAX_TEMPLATE_CHARS:,} characters") + stripped = text.lstrip(" \t\r\n") + if stripped.startswith("{"): + try: + data = json.loads(stripped) + except json.JSONDecodeError as exc: + offset = len(text) - len(stripped) + line = exc.lineno + text[:offset].count("\n") + raise CfnError(f"Invalid JSON: {exc.msg}", line, exc.colno) from exc + except RecursionError as exc: + raise CfnError("Template nested too deeply") from exc + else: + try: + check_yaml_limits(text, max_depth=MAX_DEPTH, max_nodes=MAX_NODES) + loader = CfnLoader(text) + try: + data = loader.get_single_data() + finally: + loader.dispose() + except yaml.YAMLError as exc: + raise syntax_error(exc) from exc + except ValueError as exc: + # check_yaml_limits raises YamlLimitError, a ValueError with a user-safe message. + if isinstance(exc, CfnError): + raise + raise CfnError(getattr(exc, "message", "Template too large")) from exc + check_shape(data) + validate_template(data) + return data + + +def validate_template(data: Any) -> None: + """The structure every template needs: a mapping with a non-empty Resources mapping, + each resource a mapping with a Type.""" + if not isinstance(data, dict): + raise CfnError("Invalid template: the top level must be a mapping") + resources = data.get("Resources") + if not resources: + raise CfnError("Invalid template: no 'Resources' defined") + if not isinstance(resources, dict): + raise CfnError("Invalid template: 'Resources' must be a mapping") + for logical_id, resource in resources.items(): + if not isinstance(resource, dict): + raise CfnError(f"Invalid template: resource '{logical_id}' must be a mapping") + kind = resource.get("Type") + if not isinstance(kind, str) or not kind: + raise CfnError(f"Invalid template: resource '{logical_id}' has no 'Type'") + properties = resource.get("Properties") + if properties is not None and not isinstance(properties, dict): + raise CfnError(f"Invalid template: 'Properties' of '{logical_id}' must be a mapping") + for section in ("Parameters", "Mappings", "Conditions", "Outputs"): + value = data.get(section) + if value is not None and not isinstance(value, dict): + raise CfnError(f"Invalid template: '{section}' must be a mapping") + for name, parameter in (data.get("Parameters") or {}).items(): + if not isinstance(parameter, dict) or not isinstance(parameter.get("Type"), str): + raise CfnError(f"Invalid template: parameter '{name}' needs a 'Type'") + for name, output in (data.get("Outputs") or {}).items(): + if not isinstance(output, dict) or "Value" not in output: + raise CfnError(f"Invalid template: output '{name}' needs a 'Value'") + for section in ("Resources", "Parameters", "Conditions", "Mappings", "Outputs"): + for name in data.get(section) or {}: + if not isinstance(name, str) or not NAME.match(name): + raise CfnError( + f"Invalid template: '{name}' in {section} must be letters and digits only " + "(A-Z, a-z, 0-9)" + ) + + +def transforms(template: dict[str, Any]) -> list[str]: + """The names of the transforms the template declares.""" + value = template.get("Transform") + if value is None: + return [] + items = value if isinstance(value, list) else [value] + return [item if isinstance(item, str) else "AWS::Include" for item in items] + + +def detect_source(template: dict[str, Any]) -> str: + """'sam', 'cdk' or 'cloudformation'.""" + if SAM_TRANSFORM in transforms(template): + return "sam" + for resource in template["Resources"].values(): + if resource.get("Type") == "AWS::CDK::Metadata": + return "cdk" + metadata = resource.get("Metadata") + if isinstance(metadata, dict) and "aws:cdk:path" in metadata: + return "cdk" + return "cloudformation" + + +def unknown_sections(template: dict[str, Any]) -> list[str]: + """Top-level sections that are no part of a CloudFormation template.""" + return [str(name) for name in template if name not in TOP_LEVEL] diff --git a/services/converter-api/converters/cfn/pipeline.py b/services/converter-api/converters/cfn/pipeline.py new file mode 100644 index 0000000..2c15448 --- /dev/null +++ b/services/converter-api/converters/cfn/pipeline.py @@ -0,0 +1,103 @@ +"""The whole conversion: template text in, Terraform files and notes out. + +result = convert_template(open("template.yaml").read()) +result["files"] # [{"path": "main.tf", "content": "..."}, ...] +result["notes"] # what needs a human decision +result["resources"] # each CloudFormation resource and where it went +result["source"] # "cloudformation", "sam" or "cdk" +""" + +from __future__ import annotations + +from typing import Any + +from converters.cfn.cdk import prepare_cdk +from converters.cfn.constants import LANGUAGE_EXTENSIONS, LAYOUTS, PROVIDERS, SAM_TRANSFORM +from converters.cfn.convert import Converter +from converters.cfn.errors import CfnError +from converters.cfn.parse import detect_source, load_template, transforms, unknown_sections +from converters.cfn.sam import expand_sam + + +class TemplateConverter: + """Reads a template, expands SAM or cleans up CDK output, and converts the result.""" + + def __init__( + self, + provider: str = "aws", + layout: str = "files", + stack_name: str | None = None, + include_imports: bool = False, + ) -> None: + """Conversion options. provider: "aws" (hand-written mappings, awscc for the rest) + or "awscc" (awscc only). layout: "files" (versions.tf, variables.tf, main.tf...) or + "single" (main.tf).""" + if provider not in PROVIDERS: + raise CfnError(f"Unknown provider '{provider}'. Use one of: {', '.join(PROVIDERS)}") + if layout not in LAYOUTS: + raise CfnError(f"Unknown layout '{layout}'. Use one of: {', '.join(LAYOUTS)}") + self.provider = provider + self.layout = layout + self.stack_name = stack_name + self.include_imports = include_imports + + def convert(self, text: str) -> dict[str, Any]: + """Convert template text (JSON or YAML). Raises CfnError for input it cannot + convert.""" + template = load_template(text) + source = detect_source(template) + notes = self.template_notes(template) + names: dict[str, str] = {} + hints: dict[str, dict[str, Any]] = {} + if source == "sam": + template, hints = expand_sam(template, notes) + elif source == "cdk": + template, names, hints = prepare_cdk(template, notes) + if template.get("Rules"): + notes.append( + "The Rules of the template were not converted; add the checks as variable " + "validation blocks or preconditions" + ) + converter = Converter( + template, self.provider, self.stack_name, self.include_imports, names, hints + ) + result = converter.run(self.layout) + return { + "source": source, + "files": result["files"], + "notes": notes + result["notes"], + "resources": result["resources"], + "summary": self.summary(result["resources"]), + } + + def template_notes(self, template: dict[str, Any]) -> list[str]: + """Notes about the template as a whole: unknown sections and transforms.""" + notes = [ + f"Top-level section '{name}' is no part of a CloudFormation template and was ignored" + for name in unknown_sections(template) + ] + for name in transforms(template): + if name not in (SAM_TRANSFORM, LANGUAGE_EXTENSIONS): + notes.append( + f"Transform '{name}' runs inside CloudFormation and was not applied; " + "convert the template it produces instead" + ) + return notes + + def summary(self, resources: list[dict[str, Any]]) -> dict[str, int]: + """How many resources went to each provider, and how many were not converted.""" + counts = {"resources": len(resources), "aws": 0, "awscc": 0, "unsupported": 0} + for entry in resources: + counts[entry["status"]] += 1 + return counts + + +def convert_template( + text: str, + provider: str = "aws", + layout: str = "files", + stack_name: str | None = None, + include_imports: bool = False, +) -> dict[str, Any]: + """Convert template text with the given options. See TemplateConverter.""" + return TemplateConverter(provider, layout, stack_name, include_imports).convert(text) diff --git a/services/converter-api/converters/cfn/resources/__init__.py b/services/converter-api/converters/cfn/resources/__init__.py new file mode 100644 index 0000000..4c363d3 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/__init__.py @@ -0,0 +1,2 @@ +"""Hand-written mappings from CloudFormation resource types to the `aws` Terraform provider, +one ResourceConverter subclass per type (base.py), listed in registry.py.""" diff --git a/services/converter-api/converters/cfn/resources/apigateway.py b/services/converter-api/converters/cfn/resources/apigateway.py new file mode 100644 index 0000000..4f3001a --- /dev/null +++ b/services/converter-api/converters/cfn/resources/apigateway.py @@ -0,0 +1,607 @@ +"""API Gateway REST APIs (v1) and HTTP/WebSocket APIs (v2).""" + +from __future__ import annotations + +import re +from typing import Any + +from converters.cfn.builder import Builder, Props +from converters.cfn.context import Context +from converters.cfn.models import BLANK, Attr, Block, Raw +from converters.cfn.resources.base import ResourceConverter +from converters.cfn.resources.compute import both, literal_bool, optional_block + + +def body_title(b: Builder) -> str | None: + """The OpenAPI title, which API Gateway uses as the name when Name is left out.""" + body = b.props.peek("Body") + info = body.get("info") if isinstance(body, dict) else None + title = info.get("title") if isinstance(info, dict) else None + return title if isinstance(title, str) else None + + +def api_name(b: Builder) -> None: + """The name of an API: Name, else the OpenAPI title, else one made from the stack name.""" + title = body_title(b) + if not b.props.has("Name") and title: + b.props.drop("Name") + b.props.set("name", title) + else: + b.name_attr("name", "Name") + + +def body_location(b: Builder) -> None: + """BodyS3Location, which is reported: Terraform reads the body from a local file.""" + if b.props.take("BodyS3Location") is not None: + b.ctx.note( + f"{b.logical_id}: BodyS3Location was not converted; download the OpenAPI file next " + 'to the Terraform files and set body = file("${path.module}/")' + ) + + +def name_suffix(value: Any, index: int) -> str: + """'_200' for a status code, or the position when the code is computed.""" + if isinstance(value, str | int) and not isinstance(value, bool): + cleaned = re.sub(r"[^a-z0-9_]+", "_", str(value).lower()).strip("_") + if cleaned: + return f"_{cleaned}" + return f"_{index}" + + +def number_text(ctx: Context, value: Any) -> Any: + """A number as text, for the arguments Terraform takes as strings where CloudFormation + takes numbers (minimum_compression_size, status codes).""" + if isinstance(value, int | float) and not isinstance(value, bool): + return str(value) + return ctx.expr(value) + + +def text_attr(p: Props, tf_name: str, cfn_name: str) -> bool: + """A property copied as text (see number_text) when it is present. Returns whether it + was present.""" + value = p.take(cfn_name) + if value is None: + return False + p.set(tf_name, number_text(p.ctx, value)) + return True + + +def method_path(resource_path: Any, http_method: Any) -> Any: + """ResourcePath ('/~1pets', '/*') and HttpMethod in CloudFormation as method_path in + Terraform ('pets/GET', '*/*'). The root resource ('/') is '~1', as API Gateway encodes + it in method setting paths.""" + if not (isinstance(resource_path, str) and isinstance(http_method, str)): + return None + path = resource_path.replace("~1", "/").lstrip("/") or "~1" + return f"{path}/{http_method}" + + +def fill_access_log_settings(a: Props) -> None: + """The access_log_settings block of a REST or HTTP stage.""" + a.attrs({"destination_arn": "DestinationArn", "format": "Format"}) + + +# --- REST APIs (v1) --------------------------------------------------------------------- + + +class RestApi(ResourceConverter): + """AWS::ApiGateway::RestApi as aws_api_gateway_rest_api.""" + + cfn_type = "AWS::ApiGateway::RestApi" + tf_type = "aws_api_gateway_rest_api" + attrs = {"RootResourceId": "root_resource_id", "RestApiId": "id", "Arn": "arn"} + + def convert(self, b: Builder) -> None: + """The API, its body and settings.""" + p = b.props + api_name(b) + p.attr("description", "Description") + p.json("body", "Body") + body_location(b) + p.json("policy", "Policy") + p.list_attr("binary_media_types", "BinaryMediaTypes") + p.attr("api_key_source", "ApiKeySourceType") + text_attr(p, "minimum_compression_size", "MinimumCompressionSize") + p.boolean("disable_execute_api_endpoint", "DisableExecuteApiEndpoint") + p.boolean("fail_on_warnings", "FailOnWarnings") + p.attr("parameters", "Parameters") + p.attr("put_rest_api_mode", "Mode") + p.block("endpoint_configuration", "EndpointConfiguration", self.fill_endpoint) + p.tags() + + def fill_endpoint(self, e: Props) -> None: + """The endpoint_configuration block.""" + e.list_attr("types", "Types") + e.list_attr("vpc_endpoint_ids", "VpcEndpointIds") + e.attr("ip_address_type", "IpAddressType") + + +class RestDeployment(ResourceConverter): + """AWS::ApiGateway::Deployment as aws_api_gateway_deployment, with its stage as a + separate resource.""" + + cfn_type = "AWS::ApiGateway::Deployment" + tf_type = "aws_api_gateway_deployment" + attrs = {"DeploymentId": "id"} + + def convert(self, b: Builder) -> None: + """The deployment, redeployed when the API body changes, and its stage.""" + p = b.props + rest_api_id = p.peek("RestApiId") + p.attr("rest_api_id", "RestApiId") + p.attr("description", "Description") + body = self.rest_api_body(b, rest_api_id) + if body is not None: + # A deployment is a snapshot: redeploy whenever the API definition changes. + p.set("triggers", {"redeployment": Raw(f"sha1({body})")}) + else: + b.ctx.note( + f"{b.logical_id}: a Terraform deployment is only redeployed when its arguments " + "change; add triggers (e.g. a hash of the methods and integrations) so API " + "changes get deployed" + ) + b.lifecycle.append(Attr("create_before_destroy", True)) + stage_name = p.take("StageName") + stage = p.take("StageDescription") + if stage_name is None: + return + # Provider v6 removed stage_name from deployments: the stage is its own resource. + inner = Props(b.ctx, stage, f"{b.logical_id}.StageDescription", p.owner) + inner.attr("description", "Description") + inner.boolean("xray_tracing_enabled", "TracingEnabled") + inner.attr("variables", "Variables") + inner.finish() + b.add_resource( + "aws_api_gateway_stage", + "_stage", + [ + Attr("rest_api_id", b.ctx.expr(rest_api_id)), + Attr("deployment_id", b.self_ref("id")), + Attr("stage_name", b.ctx.expr(stage_name)), + ] + + inner.items, + ) + + def rest_api_body(self, b: Builder, value: Any) -> str | None: + """`.body` when RestApiId refers to a REST API in this template with a + Body.""" + if not (isinstance(value, dict) and set(value) == {"Ref"}): + return None + target = value["Ref"] + other = b.ctx.template["Resources"].get(target) + info = b.ctx.resources.get(str(target)) + if ( + isinstance(other, dict) + and other.get("Type") == "AWS::ApiGateway::RestApi" + and (other.get("Properties") or {}).get("Body") is not None + and info is not None + and info.kind == "aws" + ): + return info.expression("body") + return None + + +class RestStage(ResourceConverter): + """AWS::ApiGateway::Stage as aws_api_gateway_stage, with its method settings as + separate resources.""" + + cfn_type = "AWS::ApiGateway::Stage" + tf_type = "aws_api_gateway_stage" + ref = "stage_name" + attrs = {"Arn": "arn"} + + def convert(self, b: Builder) -> None: + """The stage, then one aws_api_gateway_method_settings per MethodSettings entry.""" + p = b.props + rest_api_id = p.peek("RestApiId") + p.attr("rest_api_id", "RestApiId") + p.attr("deployment_id", "DeploymentId") + b.name_attr("stage_name", "StageName") + p.attrs( + { + "description": "Description", + "variables": "Variables", + "cache_cluster_size": "CacheClusterSize", + "client_certificate_id": "ClientCertificateId", + "documentation_version": "DocumentationVersion", + } + ) + p.boolean("xray_tracing_enabled", "TracingEnabled") + p.boolean("cache_cluster_enabled", "CacheClusterEnabled") + p.block("access_log_settings", "AccessLogSetting", fill_access_log_settings) + p.tags() + for index, item in enumerate(p.literal("MethodSettings", list) or [], start=1): + when, setting = b.ctx.optional_item(item) + setting = p.literal("MethodSettings", dict, value=setting) + if setting is not None: + self.method_settings(b, rest_api_id, setting, index, when) + + def method_settings( + self, b: Builder, rest_api_id: Any, setting: Any, index: int, when: str | None + ) -> None: + """One MethodSettings entry as aws_api_gateway_method_settings.""" + inner = Props(b.ctx, setting, f"{b.logical_id}.MethodSettings[{index - 1}]", b.props.owner) + path = method_path(inner.take("ResourcePath", "/*"), inner.take("HttpMethod", "*")) + if path is None: + b.ctx.note( + f"{b.logical_id}: MethodSettings[{index - 1}] uses a computed path or method; " + "set method_path by hand" + ) + path = "*/*" + inner.boolean("metrics_enabled", "MetricsEnabled") + inner.boolean("data_trace_enabled", "DataTraceEnabled") + inner.boolean("caching_enabled", "CachingEnabled") + inner.boolean("cache_data_encrypted", "CacheDataEncrypted") + inner.attr("logging_level", "LoggingLevel") + inner.number("cache_ttl_in_seconds", "CacheTtlInSeconds") + inner.number("throttling_burst_limit", "ThrottlingBurstLimit") + inner.number("throttling_rate_limit", "ThrottlingRateLimit") + inner.finish() + b.add_resource( + "aws_api_gateway_method_settings", + f"_settings_{index}", + [ + Attr("rest_api_id", b.ctx.expr(rest_api_id)), + Attr("stage_name", b.self_ref("stage_name")), + Attr("method_path", path), + Block("settings", [], inner.items), + ], + when=when, + ) + + +class RestResource(ResourceConverter): + """AWS::ApiGateway::Resource as aws_api_gateway_resource.""" + + cfn_type = "AWS::ApiGateway::Resource" + tf_type = "aws_api_gateway_resource" + attrs = {"ResourceId": "id"} + + def convert(self, b: Builder) -> None: + """The API, parent and path part of the resource.""" + b.props.attrs( + {"rest_api_id": "RestApiId", "parent_id": "ParentId", "path_part": "PathPart"} + ) + + +class RestMethod(ResourceConverter): + """AWS::ApiGateway::Method as aws_api_gateway_method, with its integration and responses + as the separate resources Terraform uses for them.""" + + cfn_type = "AWS::ApiGateway::Method" + tf_type = "aws_api_gateway_method" + + def convert(self, b: Builder) -> None: + """The method, its responses, its integration and the integration responses.""" + p = b.props + rest_api_id = p.peek("RestApiId") + resource_id = p.peek("ResourceId") + p.attrs( + { + "rest_api_id": "RestApiId", + "resource_id": "ResourceId", + "http_method": "HttpMethod", + "authorizer_id": "AuthorizerId", + "operation_name": "OperationName", + "request_parameters": "RequestParameters", + "request_models": "RequestModels", + "request_validator_id": "RequestValidatorId", + } + ) + if not p.attr("authorization", "AuthorizationType"): + p.set("authorization", "NONE") + p.boolean("api_key_required", "ApiKeyRequired") + p.list_attr("authorization_scopes", "AuthorizationScopes") + shared = [ + Attr("rest_api_id", b.ctx.expr(rest_api_id)), + Attr("resource_id", b.ctx.expr(resource_id)), + Attr("http_method", b.self_ref("http_method")), + ] + responses = self.method_responses(b, shared) + self.integration(b, shared, responses) + + def method_responses(self, b: Builder, shared: list[Any]) -> dict[str, str]: + """One aws_api_gateway_method_response per MethodResponses entry. Returns their + addresses by status code.""" + p = b.props + responses: dict[str, str] = {} + for index, item in enumerate(p.literal("MethodResponses", list) or []): + when, response = b.ctx.optional_item(item) + response = p.literal("MethodResponses", dict, value=response) + if response is None: + continue + inner = Props(b.ctx, response, f"{b.logical_id}.MethodResponses[{index}]", p.owner) + status = inner.peek("StatusCode") + text_attr(inner, "status_code", "StatusCode") + inner.attrs( + {"response_models": "ResponseModels", "response_parameters": "ResponseParameters"} + ) + inner.finish() + responses[str(status)] = b.add_resource( + "aws_api_gateway_method_response", + f"_response{name_suffix(status, index)}", + shared + inner.items, + when=when, + ) + return responses + + def integration(self, b: Builder, shared: list[Any], responses: dict[str, str]) -> None: + """Integration as aws_api_gateway_integration plus one + aws_api_gateway_integration_response per IntegrationResponses entry, each after the + method response for its status code (in `responses`).""" + p = b.props + integration_when, integration = b.ctx.optional_item(p.take("Integration")) + integration = p.literal("Integration", dict, value=integration) + if integration is None: + return + inner = Props(b.ctx, integration, f"{b.logical_id}.Integration", p.owner) + inner.attrs( + { + "type": "Type", + "integration_http_method": "IntegrationHttpMethod", + "uri": "Uri", + "credentials": "Credentials", + "request_templates": "RequestTemplates", + "request_parameters": "RequestParameters", + "passthrough_behavior": "PassthroughBehavior", + "content_handling": "ContentHandling", + "connection_type": "ConnectionType", + "connection_id": "ConnectionId", + "cache_namespace": "CacheNamespace", + } + ) + inner.number("timeout_milliseconds", "TimeoutInMillis") + inner.list_attr("cache_key_parameters", "CacheKeyParameters") + integration_responses = inner.literal("IntegrationResponses", list) or [] + inner.finish() + integration_address = b.add_resource( + "aws_api_gateway_integration", + "_integration", + shared + inner.items, + when=integration_when, + ) + for index, entry in enumerate(integration_responses): + when, response = b.ctx.optional_item(entry) + response = p.literal("Integration.IntegrationResponses", dict, value=response) + if response is None: + continue + where = f"{b.logical_id}.Integration.IntegrationResponses[{index}]" + item = Props(b.ctx, response, where, p.owner) + status = item.peek("StatusCode") + text_attr(item, "status_code", "StatusCode") + item.attrs( + { + "selection_pattern": "SelectionPattern", + "response_templates": "ResponseTemplates", + "response_parameters": "ResponseParameters", + "content_handling": "ContentHandling", + } + ) + item.finish() + # The method response for the same status code must exist first. + depends = [Raw(integration_address)] + if str(status) in responses: + depends.append(Raw(responses[str(status)])) + b.add_resource( + "aws_api_gateway_integration_response", + f"_integration_response{name_suffix(status, index)}", + shared + item.items + [BLANK, Attr("depends_on", depends)], + when=both(integration_when, when), + ) + + +# --- HTTP and WebSocket APIs (v2) ------------------------------------------------------- + + +class HttpApi(ResourceConverter): + """AWS::ApiGatewayV2::Api as aws_apigatewayv2_api.""" + + cfn_type = "AWS::ApiGatewayV2::Api" + tf_type = "aws_apigatewayv2_api" + attrs = {"ApiEndpoint": "api_endpoint", "ApiId": "id"} + + def convert(self, b: Builder) -> None: + """The API, its body and CORS settings.""" + p = b.props + api_name(b) + if not p.attr("protocol_type", "ProtocolType"): + # Only an imported OpenAPI body can leave it out, and that is always HTTP. + p.set("protocol_type", "HTTP") + p.attrs( + { + "description": "Description", + "route_selection_expression": "RouteSelectionExpression", + "api_key_selection_expression": "ApiKeySelectionExpression", + "version": "Version", + "credentials_arn": "CredentialsArn", + "route_key": "RouteKey", + "target": "Target", + "ip_address_type": "IpAddressType", + } + ) + p.json("body", "Body") + body_location(b) + p.boolean("disable_execute_api_endpoint", "DisableExecuteApiEndpoint") + p.boolean("fail_on_warnings", "FailOnWarnings") + p.block("cors_configuration", "CorsConfiguration", self.fill_cors) + p.tags() + + def fill_cors(self, c: Props) -> None: + """The cors_configuration block.""" + c.boolean("allow_credentials", "AllowCredentials") + c.list_attr("allow_headers", "AllowHeaders") + c.list_attr("allow_methods", "AllowMethods") + c.list_attr("allow_origins", "AllowOrigins") + c.list_attr("expose_headers", "ExposeHeaders") + c.number("max_age", "MaxAge") + + +class HttpIntegration(ResourceConverter): + """AWS::ApiGatewayV2::Integration as aws_apigatewayv2_integration.""" + + cfn_type = "AWS::ApiGatewayV2::Integration" + tf_type = "aws_apigatewayv2_integration" + attrs = {"IntegrationId": "id"} + + def convert(self, b: Builder) -> None: + """The integration and its TLS settings.""" + p = b.props + p.attrs( + { + "api_id": "ApiId", + "integration_type": "IntegrationType", + "integration_uri": "IntegrationUri", + "integration_method": "IntegrationMethod", + "integration_subtype": "IntegrationSubtype", + "payload_format_version": "PayloadFormatVersion", + "connection_type": "ConnectionType", + "connection_id": "ConnectionId", + "credentials_arn": "CredentialsArn", + "description": "Description", + "passthrough_behavior": "PassthroughBehavior", + "request_parameters": "RequestParameters", + "request_templates": "RequestTemplates", + "template_selection_expression": "TemplateSelectionExpression", + "content_handling_strategy": "ContentHandlingStrategy", + } + ) + p.number("timeout_milliseconds", "TimeoutInMillis") + p.block("tls_config", "TlsConfig", self.fill_tls_config) + + def fill_tls_config(self, t: Props) -> None: + """The tls_config block.""" + t.attr("server_name_to_verify", "ServerNameToVerify") + + +class HttpRoute(ResourceConverter): + """AWS::ApiGatewayV2::Route as aws_apigatewayv2_route.""" + + cfn_type = "AWS::ApiGatewayV2::Route" + tf_type = "aws_apigatewayv2_route" + attrs = {"RouteId": "id"} + + def convert(self, b: Builder) -> None: + """The route and its request parameters.""" + p = b.props + p.attrs( + { + "api_id": "ApiId", + "route_key": "RouteKey", + "target": "Target", + "authorization_type": "AuthorizationType", + "authorizer_id": "AuthorizerId", + "operation_name": "OperationName", + "request_models": "RequestModels", + "model_selection_expression": "ModelSelectionExpression", + "route_response_selection_expression": "RouteResponseSelectionExpression", + } + ) + p.boolean("api_key_required", "ApiKeyRequired") + p.list_attr("authorization_scopes", "AuthorizationScopes") + for key, entry in (p.literal("RequestParameters", dict) or {}).items(): + when, value = b.ctx.optional_item(entry) + if isinstance(value, dict): + value = p.literal(f"RequestParameters.{key}", dict, value=value) + if value is None: + continue + value = value.get("Required", False) + p.items.append( + optional_block( + "request_parameter", + [ + Attr("request_parameter_key", str(key)), + Attr("required", literal_bool(b.ctx.expr(value))), + ], + when, + ) + ) + + +def fill_route_settings(r: Props) -> None: + """The throttling, logging and metrics settings of a route, or of all routes.""" + r.boolean("data_trace_enabled", "DataTraceEnabled") + r.boolean("detailed_metrics_enabled", "DetailedMetricsEnabled") + r.attr("logging_level", "LoggingLevel") + r.number("throttling_burst_limit", "ThrottlingBurstLimit") + r.number("throttling_rate_limit", "ThrottlingRateLimit") + + +class HttpStage(ResourceConverter): + """AWS::ApiGatewayV2::Stage as aws_apigatewayv2_stage.""" + + cfn_type = "AWS::ApiGatewayV2::Stage" + tf_type = "aws_apigatewayv2_stage" + ref = "name" + + def convert(self, b: Builder) -> None: + """The stage, its logging and its route settings.""" + p = b.props + p.attr("api_id", "ApiId") + b.name_attr("name", "StageName") + p.attrs( + { + "deployment_id": "DeploymentId", + "description": "Description", + "stage_variables": "StageVariables", + "client_certificate_id": "ClientCertificateId", + } + ) + p.boolean("auto_deploy", "AutoDeploy") + p.block("access_log_settings", "AccessLogSettings", fill_access_log_settings) + p.block("default_route_settings", "DefaultRouteSettings", fill_route_settings) + for route_key, entry in (p.literal("RouteSettings", dict) or {}).items(): + when, settings = b.ctx.optional_item(entry) + settings = p.literal(f"RouteSettings.{route_key}", dict, value=settings) + if settings is None: + continue + inner = Props(b.ctx, settings, f"{b.logical_id}.RouteSettings.{route_key}", p.owner) + inner.set("route_key", str(route_key)) + fill_route_settings(inner) + inner.finish() + p.items.append(optional_block("route_settings", inner.items, when)) + p.tags() + + +class HttpAuthorizer(ResourceConverter): + """AWS::ApiGatewayV2::Authorizer as aws_apigatewayv2_authorizer.""" + + cfn_type = "AWS::ApiGatewayV2::Authorizer" + tf_type = "aws_apigatewayv2_authorizer" + attrs = {"AuthorizerId": "id"} + + def convert(self, b: Builder) -> None: + """The authorizer and its JWT settings.""" + p = b.props + p.attr("api_id", "ApiId") + b.name_attr("name", "Name") + p.attrs( + { + "authorizer_type": "AuthorizerType", + "authorizer_uri": "AuthorizerUri", + "authorizer_credentials_arn": "AuthorizerCredentialsArn", + "authorizer_payload_format_version": "AuthorizerPayloadFormatVersion", + } + ) + p.number("authorizer_result_ttl_in_seconds", "AuthorizerResultTtlInSeconds") + p.boolean("enable_simple_responses", "EnableSimpleResponses") + p.list_attr("identity_sources", "IdentitySource") + p.block("jwt_configuration", "JwtConfiguration", self.fill_jwt_configuration) + + def fill_jwt_configuration(self, j: Props) -> None: + """The jwt_configuration block.""" + j.list_attr("audience", "Audience") + j.attr("issuer", "Issuer") + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + RestApi, + RestDeployment, + RestStage, + RestResource, + RestMethod, + HttpApi, + HttpIntegration, + HttpRoute, + HttpStage, + HttpAuthorizer, +) diff --git a/services/converter-api/converters/cfn/resources/base.py b/services/converter-api/converters/cfn/resources/base.py new file mode 100644 index 0000000..2394d53 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/base.py @@ -0,0 +1,43 @@ +"""The base class of every hand-written CloudFormation to `aws` provider mapping.""" + +from __future__ import annotations + +from typing import Any, ClassVar + +from converters.cfn.builder import Builder +from converters.cfn.models import ResourceInfo + + +class ResourceConverter: + """Converts one CloudFormation resource type to the `aws` provider. + + A subclass names the types it maps between and how references read it: + + class SqsQueue(ResourceConverter): + cfn_type = "AWS::SQS::Queue" + tf_type = "aws_sqs_queue" + ref = "url" + attrs = {"Arn": "arn", "QueueName": "name"} + + def convert(self, b: Builder) -> None: + b.props.number("visibility_timeout_seconds", "VisibilityTimeout") + + and lists itself in its module's CONVERTERS, which ResourceRegistry reads. + """ + + cfn_type: ClassVar[str] = "" + tf_type: ClassVar[str] = "" + # The attribute `Ref` returns. + ref: ClassVar[str] = "id" + # Fn::GetAtt attribute name -> Terraform attribute. + attrs: ClassVar[dict[str, str]] = {} + # The property whose literal value is the resource's import ID, if there is one. + import_id: ClassVar[str | None] = None + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """Adjust where references point, before any resource is converted. Runs for every + resource of this type; the default changes nothing.""" + + def convert(self, b: Builder) -> None: + """Turn the resource's properties into Terraform. Properties left in `b.props` are + reported as not converted.""" diff --git a/services/converter-api/converters/cfn/resources/compute.py b/services/converter-api/converters/cfn/resources/compute.py new file mode 100644 index 0000000..fbd0a79 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/compute.py @@ -0,0 +1,1280 @@ +"""Lambda, EC2 instances and launch templates, and ECS.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Callable +from typing import Any, ClassVar + +from converters.cfn import hcl +from converters.cfn.builder import Builder, Props, snippet, tags_map +from converters.cfn.expressions import intrinsic_name, wrap_operand +from converters.cfn.models import BLANK, Attr, Block, Call, Raw +from converters.cfn.resources.base import ResourceConverter + + +def optional_block(kind: str, items: list[Any], when: str | None) -> Block: + """A nested block, or (for an `!If [C, {...}, !Ref AWS::NoValue]` item) a dynamic block + present only `when` the condition holds.""" + if when is None: + return Block(kind, [], items) + return Block( + "dynamic", + [kind], + [Attr("for_each", Raw(f"{when} ? [1] : []")), Block("content", [], items)], + ) + + +def both(first: str | None, second: str | None) -> str | None: + """Two optional conditions that must both hold.""" + if first and second: + return f"{first} && {second}" + return first or second + + +def literal_bool(value: Any) -> Any: + """A "true" or "false" text (any case) as a boolean; anything else unchanged.""" + if isinstance(value, str) and value.lower() in ("true", "false"): + return value.lower() == "true" + return value + + +def snippet_text(value: Any) -> str: + """All the text in a value, intrinsic functions included, for searching.""" + return json.dumps(value, default=str) + + +# --- Lambda code ------------------------------------------------------------------------ + + +class LambdaCode: + """The code of one Lambda function or layer: a local file or folder, an S3 object, an + image or inline source.""" + + extensions: ClassVar[tuple[tuple[str, str], ...]] = ( + ("python", ".py"), + ("nodejs", ".js"), + ("ruby", ".rb"), + ) + archives: ClassVar[tuple[str, ...]] = (".zip", ".jar") + + def __init__(self, b: Builder) -> None: + """The code of the function or layer `b` builds.""" + self.b = b + + @classmethod + def inline_filename(cls, handler: Any, runtime: Any) -> str: + """The file inline code must be saved as: the module of the handler plus the + extension of the runtime ('index.handler' on nodejs20.x -> 'index.js').""" + module = "index" + if isinstance(handler, str) and "." in handler: + module = handler.rsplit(".", 1)[0] + extension = ".py" + if isinstance(runtime, str): + for prefix, candidate in cls.extensions: + if runtime.startswith(prefix): + extension = candidate + return module + extension + + def module_path(self, path: str) -> str: + """A path relative to the Terraform files, as an HCL template string.""" + if path.startswith("./"): + path = path[2:] + return '"${path.module}/' + hcl.template_text(path) + '"' + + def use_archive(self, p: Props, archive: str) -> None: + """Point the function at the zip file the archive_file data source `archive` makes.""" + self.b.hints["archive"] = True + p.set("filename", Raw(f"{archive}.output_path")) + p.set("source_code_hash", Raw(f"{archive}.output_base64sha256")) + + def archive(self, items: list[Any]) -> str: + """An archive_file data source zipping `items`. Returns its address.""" + b = self.b + return b.add_data( + "archive_file", + "_code", + [ + Attr("type", "zip"), + Attr("output_path", Raw(f'"${{path.module}}/build/{b.info.name}.zip"')), + ] + + items, + ) + + def local_code(self, p: Props, path: str) -> None: + """Code from a local path (SAM CodeUri, CDK asset): a zip or jar file used as is, or a + directory zipped by the archive provider.""" + location = self.module_path(path) + if path.lower().endswith(self.archives): + p.set("filename", Raw(location)) + p.set("source_code_hash", Raw(f"filebase64sha256({location})")) + return + self.use_archive(p, self.archive([Attr("source_dir", Raw(location))])) + + def convert(self, p: Props, cfn_name: str) -> None: + """Code (functions) or Content (layers) as filename, s3_* or image_uri.""" + b = self.b + path = b.hints.get("code_path") + if isinstance(path, str) and path: + # SAM and CDK point at local files; the S3 location in the template is a placeholder. + p.drop(cfn_name) + self.local_code(p, path) + return + code = p.take(cfn_name) + if code is None: + return + inner = Props(b.ctx, code, f"{b.logical_id}.{cfn_name}", p.owner) + inner.attrs( + { + "s3_bucket": "S3Bucket", + "s3_key": "S3Key", + "s3_object_version": "S3ObjectVersion", + "source_kms_key_arn": "SourceKMSKeyArn", + } + ) + # Read from the template: PackageType, Handler and Runtime leave p before Code. + original = b.resource.get("Properties") or {} + if inner.attr("image_uri", "ImageUri") and "PackageType" not in original: + inner.set("package_type", "Image") + source = inner.take("ZipFile") + if source is not None: + if re.search(r"cfn-?response", snippet_text(source)): + b.ctx.note( + f"{b.logical_id}: the inline code uses the cfn-response module, which " + "CloudFormation adds to ZipFile code; Terraform does not, so add the module " + "to the archive (or send the response yourself)" + ) + filename = self.inline_filename(original.get("Handler"), original.get("Runtime")) + content = [Attr("content", b.ctx.expr(source)), Attr("filename", filename)] + self.use_archive(inner, self.archive([BLANK, Block("source", [], content)])) + inner.finish() + p.items.extend(inner.items) + + +def function_id(b: Builder, value: Any) -> str | None: + """The logical id of the Lambda function a FunctionName value refers to, if any.""" + if not isinstance(value, dict): + return None + if set(value) == {"Ref"}: + target = value["Ref"] + elif set(value) == {"Fn::GetAtt"} and isinstance(value["Fn::GetAtt"], list): + target = value["Fn::GetAtt"][0] + else: + return None + other = b.ctx.template["Resources"].get(target) + if isinstance(other, dict) and other.get("Type") == "AWS::Lambda::Function": + return str(target) + return None + + +def has_versions(b: Builder) -> bool: + """Whether any AWS::Lambda::Version in the template points at this function.""" + for other in b.ctx.template["Resources"].values(): + if other.get("Type") == "AWS::Lambda::Version": + target = (other.get("Properties") or {}).get("FunctionName") + if function_id(b, target) == b.logical_id: + return True + return False + + +def provisioned_concurrency(b: Builder, function: Any, qualifier: Any) -> None: + """ProvisionedConcurrencyConfig of an alias or version as + aws_lambda_provisioned_concurrency_config.""" + when, config = b.ctx.optional_item(b.props.take("ProvisionedConcurrencyConfig")) + config = b.props.literal("ProvisionedConcurrencyConfig", dict, value=config) + if config is None: + return + b.add_resource( + "aws_lambda_provisioned_concurrency_config", + "_concurrency", + [ + Attr("function_name", b.ctx.expr(function)), + Attr("qualifier", qualifier), + Attr( + "provisioned_concurrent_executions", + b.ctx.expr(config.get("ProvisionedConcurrentExecutions")), + ), + ], + when=when, + ) + + +# --- Lambda ----------------------------------------------------------------------------- + + +class LambdaFunction(ResourceConverter): + """AWS::Lambda::Function as aws_lambda_function.""" + + cfn_type = "AWS::Lambda::Function" + tf_type = "aws_lambda_function" + ref = "function_name" + attrs = {"Arn": "arn"} + import_id = "FunctionName" + + def convert(self, b: Builder) -> None: + """The function, its code and its settings.""" + p = b.props + b.name_attr("function_name", "FunctionName") + p.attrs( + { + "description": "Description", + "role": "Role", + "handler": "Handler", + "runtime": "Runtime", + "package_type": "PackageType", + } + ) + LambdaCode(b).convert(p, "Code") + p.number("memory_size", "MemorySize") + p.number("timeout", "Timeout") + p.number("reserved_concurrent_executions", "ReservedConcurrentExecutions") + p.list_attr("architectures", "Architectures") + p.list_attr("layers", "Layers") + p.attr("kms_key_arn", "KmsKeyArn") + p.attr("code_signing_config_arn", "CodeSigningConfigArn") + if has_versions(b): + # The AWS::Lambda::Version resources of the template read the version this + # publishes. + p.set("publish", True) + p.block("environment", "Environment", self.fill_environment) + p.block("vpc_config", "VpcConfig", self.fill_vpc_config) + p.block("tracing_config", "TracingConfig", self.fill_tracing_config) + p.block("dead_letter_config", "DeadLetterConfig", self.fill_dead_letter_config) + p.block("ephemeral_storage", "EphemeralStorage", self.fill_ephemeral_storage) + p.block("logging_config", "LoggingConfig", self.fill_logging_config) + p.block("snap_start", "SnapStart", self.fill_snap_start) + p.block("image_config", "ImageConfig", self.fill_image_config) + p.block("file_system_config", "FileSystemConfigs", self.fill_file_system_config) + p.tags() + + def fill_environment(self, e: Props) -> None: + """The environment block.""" + e.attr("variables", "Variables") + + def fill_vpc_config(self, v: Props) -> None: + """The vpc_config block.""" + v.list_attr("security_group_ids", "SecurityGroupIds") + v.list_attr("subnet_ids", "SubnetIds") + v.boolean("ipv6_allowed_for_dual_stack", "Ipv6AllowedForDualStack") + + def fill_tracing_config(self, t: Props) -> None: + """The tracing_config block.""" + t.attr("mode", "Mode") + + def fill_dead_letter_config(self, d: Props) -> None: + """The dead_letter_config block.""" + d.attr("target_arn", "TargetArn") + + def fill_ephemeral_storage(self, e: Props) -> None: + """The ephemeral_storage block.""" + e.number("size", "Size") + + def fill_logging_config(self, r: Props) -> None: + """The logging_config block.""" + # Terraform requires log_format; the CloudFormation default is Text. + if not r.attr("log_format", "LogFormat"): + r.set("log_format", "Text") + r.attrs( + { + "application_log_level": "ApplicationLogLevel", + "system_log_level": "SystemLogLevel", + "log_group": "LogGroup", + } + ) + + def fill_snap_start(self, s: Props) -> None: + """The snap_start block.""" + s.attr("apply_on", "ApplyOn") + + def fill_image_config(self, i: Props) -> None: + """The image_config block.""" + i.list_attr("command", "Command") + i.list_attr("entry_point", "EntryPoint") + i.attr("working_directory", "WorkingDirectory") + + def fill_file_system_config(self, f: Props) -> None: + """One file_system_config block.""" + f.attrs({"arn": "Arn", "local_mount_path": "LocalMountPath"}) + + +class LambdaPermission(ResourceConverter): + """AWS::Lambda::Permission as aws_lambda_permission.""" + + cfn_type = "AWS::Lambda::Permission" + tf_type = "aws_lambda_permission" + + def convert(self, b: Builder) -> None: + """Who may invoke which function.""" + b.props.attrs( + { + "action": "Action", + "function_name": "FunctionName", + "principal": "Principal", + "source_arn": "SourceArn", + "source_account": "SourceAccount", + "event_source_token": "EventSourceToken", + "function_url_auth_type": "FunctionUrlAuthType", + "principal_org_id": "PrincipalOrgID", + } + ) + + +class LambdaEventSourceMapping(ResourceConverter): + """AWS::Lambda::EventSourceMapping as aws_lambda_event_source_mapping.""" + + cfn_type = "AWS::Lambda::EventSourceMapping" + tf_type = "aws_lambda_event_source_mapping" + ref = "uuid" + attrs = {"Id": "uuid", "EventSourceMappingArn": "arn"} + numbers: ClassVar[tuple[tuple[str, str], ...]] = ( + ("batch_size", "BatchSize"), + ("maximum_batching_window_in_seconds", "MaximumBatchingWindowInSeconds"), + ("maximum_retry_attempts", "MaximumRetryAttempts"), + ("maximum_record_age_in_seconds", "MaximumRecordAgeInSeconds"), + ("parallelization_factor", "ParallelizationFactor"), + ("tumbling_window_in_seconds", "TumblingWindowInSeconds"), + ) + + def convert(self, b: Builder) -> None: + """The mapping between an event source and a function.""" + p = b.props + p.attrs( + { + "function_name": "FunctionName", + "event_source_arn": "EventSourceArn", + "starting_position": "StartingPosition", + "kms_key_arn": "KmsKeyArn", + } + ) + p.attr("starting_position_timestamp", "StartingPositionTimestamp", self.timestamp) + p.boolean("enabled", "Enabled") + p.boolean("bisect_batch_on_function_error", "BisectBatchOnFunctionError") + for tf_name, cfn_name in self.numbers: + p.number(tf_name, cfn_name) + p.list_attr("function_response_types", "FunctionResponseTypes") + p.list_attr("queues", "Queues") + p.list_attr("topics", "Topics") + p.block("filter_criteria", "FilterCriteria", self.fill_filter_criteria) + p.block("scaling_config", "ScalingConfig", self.fill_scaling_config) + p.block("destination_config", "DestinationConfig", self.fill_destination_config) + p.block("metrics_config", "MetricsConfig", self.fill_metrics_config) + p.tags() + + def timestamp(self, value: Any) -> Any: + """CloudFormation takes seconds since the epoch; Terraform takes RFC 3339 text.""" + if isinstance(value, int | float) and not isinstance(value, bool): + return Raw(f'timeadd("1970-01-01T00:00:00Z", "{int(value)}s")') + return value + + def fill_filter_criteria(self, f: Props) -> None: + """The filter_criteria block.""" + f.block("filter", "Filters", self.fill_filter) + + def fill_filter(self, x: Props) -> None: + """One filter of the filter criteria.""" + x.json("pattern", "Pattern") + + def fill_scaling_config(self, s: Props) -> None: + """The scaling_config block.""" + s.number("maximum_concurrency", "MaximumConcurrency") + + def fill_destination_config(self, d: Props) -> None: + """The destination_config block.""" + d.block("on_failure", "OnFailure", self.fill_on_failure) + + def fill_on_failure(self, o: Props) -> None: + """Where failed records go.""" + o.attr("destination_arn", "Destination") + + def fill_metrics_config(self, m: Props) -> None: + """The metrics_config block.""" + m.list_attr("metrics", "Metrics") + + +class LambdaLayerVersion(ResourceConverter): + """AWS::Lambda::LayerVersion as aws_lambda_layer_version.""" + + cfn_type = "AWS::Lambda::LayerVersion" + tf_type = "aws_lambda_layer_version" + ref = "arn" + attrs = {"LayerVersionArn": "arn"} + + def convert(self, b: Builder) -> None: + """The layer and its content.""" + p = b.props + b.name_attr("layer_name", "LayerName") + p.attr("description", "Description") + p.attr("license_info", "LicenseInfo") + p.list_attr("compatible_runtimes", "CompatibleRuntimes") + p.list_attr("compatible_architectures", "CompatibleArchitectures") + LambdaCode(b).convert(p, "Content") + + +class LambdaUrl(ResourceConverter): + """AWS::Lambda::Url as aws_lambda_function_url.""" + + cfn_type = "AWS::Lambda::Url" + tf_type = "aws_lambda_function_url" + ref = "function_arn" + attrs = {"FunctionUrl": "function_url", "FunctionArn": "function_arn"} + + def convert(self, b: Builder) -> None: + """The function URL and its CORS settings.""" + p = b.props + p.attrs( + { + "function_name": "TargetFunctionArn", + "authorization_type": "AuthType", + "qualifier": "Qualifier", + "invoke_mode": "InvokeMode", + } + ) + p.block("cors", "Cors", self.fill_cors) + + def fill_cors(self, c: Props) -> None: + """The cors block.""" + c.boolean("allow_credentials", "AllowCredentials") + c.list_attr("allow_headers", "AllowHeaders") + c.list_attr("allow_methods", "AllowMethods") + c.list_attr("allow_origins", "AllowOrigins") + c.list_attr("expose_headers", "ExposeHeaders") + c.number("max_age", "MaxAge") + + +class LambdaAlias(ResourceConverter): + """AWS::Lambda::Alias as aws_lambda_alias.""" + + cfn_type = "AWS::Lambda::Alias" + tf_type = "aws_lambda_alias" + ref = "arn" + attrs = {"AliasArn": "arn"} + + def convert(self, b: Builder) -> None: + """The alias, its routing and its provisioned concurrency.""" + p = b.props + function = p.peek("FunctionName") + p.attrs( + { + "name": "Name", + "description": "Description", + "function_name": "FunctionName", + "function_version": "FunctionVersion", + } + ) + p.block("routing_config", "RoutingConfig", self.fill_routing_config) + provisioned_concurrency(b, function, b.self_ref("name")) + + def fill_routing_config(self, r: Props) -> None: + """The routing_config block: the weight of each additional version.""" + weights: dict[Any, Any] = {} + for entry in r.literal("AdditionalVersionWeights", list) or []: + literal_entry = r.literal("AdditionalVersionWeights", dict, value=entry) + if literal_entry is None: + continue + version = r.ctx.expr(literal_entry.get("FunctionVersion")) + weight_key = version if isinstance(version, str) else Raw(hcl.inline(version)) + weights[weight_key] = r.ctx.expr(literal_entry.get("FunctionWeight")) + r.set("additional_version_weights", weights) + + +class LambdaVersion(ResourceConverter): + """AWS::Lambda::Version as terraform_data. Terraform has no version resource: a function + with `publish = true` publishes a new version on every code change. A terraform_data + records that version so Ref and Fn::GetAtt on the CloudFormation version keep working.""" + + cfn_type = "AWS::Lambda::Version" + tf_type = "terraform_data" + ref = "output.arn" + attrs = {"Version": "output.version", "FunctionArn": "output.arn"} + + def convert(self, b: Builder) -> None: + """The version the function publishes, and its provisioned concurrency.""" + p = b.props + function = p.take("FunctionName") + target = function_id(b, function) + p.drop("Description") + p.drop("CodeSha256") + if target is not None: + info = b.ctx.resources[target] + value: dict[str, Any] = { + "arn": Raw(info.expression("qualified_arn")), + "version": Raw(info.expression("version")), + } + b.ctx.note( + f"{b.logical_id} (AWS::Lambda::Version): Terraform publishes versions from the " + f"function itself, so {info.address} has publish = true and {b.info.address} " + "records its latest version" + ) + else: + value = {"arn": b.ctx.expr(function), "version": "$LATEST"} + b.ctx.note( + f"{b.logical_id} (AWS::Lambda::Version) belongs to a function outside this " + "template: set publish = true on that function and use its version" + ) + p.set("input", value) + provisioned_concurrency(b, function, Raw(b.info.expression("output.version"))) + + +# --- EC2 instances and launch templates ------------------------------------------------- + + +def ebs_items(r: Props, with_snapshot: bool) -> None: + """The settings of an EBS volume.""" + r.attrs( + { + "volume_size": "VolumeSize", + "volume_type": "VolumeType", + "iops": "Iops", + "throughput": "Throughput", + "kms_key_id": "KmsKeyId", + } + ) + if with_snapshot: + r.attr("snapshot_id", "SnapshotId") + r.boolean("encrypted", "Encrypted") + r.boolean("delete_on_termination", "DeleteOnTermination") + + +class Ec2Instance(ResourceConverter): + """AWS::EC2::Instance as aws_instance.""" + + cfn_type = "AWS::EC2::Instance" + tf_type = "aws_instance" + attrs = { + "InstanceId": "id", + "PublicIp": "public_ip", + "PrivateIp": "private_ip", + "PublicDnsName": "public_dns", + "PrivateDnsName": "private_dns", + "AvailabilityZone": "availability_zone", + } + root_devices: ClassVar[tuple[str, ...]] = ("/dev/xvda", "/dev/sda1", "/dev/sda") + booleans: ClassVar[tuple[tuple[str, str], ...]] = ( + ("monitoring", "Monitoring"), + ("ebs_optimized", "EbsOptimized"), + ("disable_api_termination", "DisableApiTermination"), + ("source_dest_check", "SourceDestCheck"), + ) + + def convert(self, b: Builder) -> None: + """The instance, its network interface, user data and block devices.""" + p = b.props + p.attrs( + { + "ami": "ImageId", + "instance_type": "InstanceType", + "key_name": "KeyName", + "subnet_id": "SubnetId", + "availability_zone": "AvailabilityZone", + "iam_instance_profile": "IamInstanceProfile", + "private_ip": "PrivateIpAddress", + "tenancy": "Tenancy", + "placement_group": "PlacementGroupName", + "instance_initiated_shutdown_behavior": "InstanceInitiatedShutdownBehavior", + "host_id": "HostId", + } + ) + p.list_attr("vpc_security_group_ids", "SecurityGroupIds") + p.list_attr("security_groups", "SecurityGroups") + p.number("ipv6_address_count", "Ipv6AddressCount") + for tf_name, cfn_name in self.booleans: + p.boolean(tf_name, cfn_name) + self.primary_interface(b, p) + user_data = p.take("UserData") + if user_data is not None: + # CloudFormation wants UserData base64-encoded, nearly always with Fn::Base64. + if isinstance(user_data, dict) and intrinsic_name(user_data) == "Fn::Base64": + p.set("user_data", b.ctx.expr(user_data["Fn::Base64"])) + else: + p.set("user_data_base64", b.ctx.expr(user_data)) + p.block("credit_specification", "CreditSpecification", self.fill_credit_specification) + p.block("launch_template", "LaunchTemplate", self.fill_launch_template) + self.devices(b, p) + p.tags() + + def fill_credit_specification(self, c: Props) -> None: + """The credit_specification block.""" + c.attr("cpu_credits", "CPUCredits") + + def fill_launch_template(self, t: Props) -> None: + """The launch_template block.""" + t.attrs({"id": "LaunchTemplateId", "name": "LaunchTemplateName", "version": "Version"}) + + def devices(self, b: Builder, p: Props) -> None: + """BlockDeviceMappings as root, EBS and instance-store (ephemeral) device blocks.""" + for item in p.literal("BlockDeviceMappings", list) or []: + when, mapping = b.ctx.optional_item(item) + mapping = p.literal("BlockDeviceMappings", dict, value=mapping) + if mapping is None: + continue + where = f"{b.logical_id}.BlockDeviceMappings" + inner = Props(b.ctx, mapping, where, p.owner) + device = inner.take("DeviceName") + ebs = inner.take("Ebs") + virtual = inner.take("VirtualName") + no_device = inner.take("NoDevice") + if virtual is not None or no_device is not None: + kind = "ephemeral_block_device" + inner.set("device_name", b.ctx.expr(device)) + if virtual is not None: + inner.set("virtual_name", b.ctx.expr(virtual)) + else: + inner.set("no_device", True) + else: + disk = Props(b.ctx, ebs, f"{where}.Ebs", p.owner) + if device in self.root_devices: + kind = "root_block_device" + ebs_items(disk, with_snapshot=False) + b.ctx.note( + f"{b.logical_id}: block device '{device}' became root_block_device; " + "check that it is the root device of the AMI" + ) + else: + kind = "ebs_block_device" + disk.set("device_name", b.ctx.expr(device)) + ebs_items(disk, with_snapshot=True) + disk.finish() + inner.items.extend(disk.items) + inner.finish() + p.items.append(optional_block(kind, inner.items, when)) + + def primary_interface(self, b: Builder, p: Props) -> None: + """A single NetworkInterfaces entry for device 0 only says where the own subnet, + groups and public IP of the instance are. Anything more complex stays a note.""" + interfaces = p.peek("NetworkInterfaces") + if not (isinstance(interfaces, list) and len(interfaces) == 1): + return + interface = interfaces[0] + if not isinstance(interface, dict) or str(interface.get("DeviceIndex", "0")) != "0": + return + if interface.get("NetworkInterfaceId"): + return + p.drop("NetworkInterfaces") + inner = Props(b.ctx, interface, f"{b.logical_id}.NetworkInterfaces[0]", p.owner) + inner.drop("DeviceIndex") + keep = inner.take("DeleteOnTermination") + if keep is not None and not (keep is True or str(keep).lower() == "true"): + b.ctx.note( + f"{b.logical_id}: the primary network interface has DeleteOnTermination " + f"{snippet(keep)}, but the interface Terraform creates with the instance is " + "always deleted with it; to keep it, create an aws_network_interface and " + "attach it" + ) + inner.comment(f"DeleteOnTermination was not converted: {snippet(keep)}") + inner.boolean("associate_public_ip_address", "AssociatePublicIpAddress") + inner.attr("subnet_id", "SubnetId") + inner.list_attr("vpc_security_group_ids", "GroupSet") + inner.attr("private_ip", "PrivateIpAddress") + inner.number("ipv6_address_count", "Ipv6AddressCount") + inner.finish() + p.items.extend(inner.items) + + +class Ec2LaunchTemplate(ResourceConverter): + """AWS::EC2::LaunchTemplate as aws_launch_template.""" + + cfn_type = "AWS::EC2::LaunchTemplate" + tf_type = "aws_launch_template" + attrs = { + "LaunchTemplateId": "id", + "LatestVersionNumber": "latest_version", + "DefaultVersionNumber": "default_version", + } + + def convert(self, b: Builder) -> None: + """The launch template, its own tags and its LaunchTemplateData.""" + p = b.props + p.attr("name", "LaunchTemplateName") + p.attr("description", "VersionDescription") + own_tags: list[Any] = [] + for spec in p.literal("TagSpecifications", list) or []: + # The own tags of the launch template (ResourceType: launch-template). + literal_spec = p.literal("TagSpecifications", dict, value=spec) + if literal_spec is not None: + tags = p.literal("TagSpecifications.Tags", list, value=literal_spec.get("Tags")) + own_tags.extend(tags or []) + if own_tags: + p.set("tags", tags_map(b.ctx, own_tags)) + data = p.take("LaunchTemplateData") + if data is None: + return + d = Props(b.ctx, data, f"{b.logical_id}.LaunchTemplateData", p.owner) + self.fill_data(d) + d.finish() + p.items.extend(d.items) + + def fill_data(self, d: Props) -> None: + """The arguments LaunchTemplateData holds.""" + d.attrs( + { + "image_id": "ImageId", + "instance_type": "InstanceType", + "key_name": "KeyName", + "instance_initiated_shutdown_behavior": "InstanceInitiatedShutdownBehavior", + "kernel_id": "KernelId", + "ram_disk_id": "RamDiskId", + # Launch templates take UserData base64-encoded, as CloudFormation does. + "user_data": "UserData", + } + ) + d.list_attr("vpc_security_group_ids", "SecurityGroupIds") + d.list_attr("security_group_names", "SecurityGroups") + d.boolean("ebs_optimized", "EbsOptimized") + d.boolean("disable_api_termination", "DisableApiTermination") + d.boolean("disable_api_stop", "DisableApiStop") + d.block("iam_instance_profile", "IamInstanceProfile", self.fill_iam_instance_profile) + d.block("block_device_mappings", "BlockDeviceMappings", self.fill_device) + d.block("metadata_options", "MetadataOptions", self.fill_metadata_options) + d.block("monitoring", "Monitoring", self.fill_monitoring) + d.block("credit_specification", "CreditSpecification", self.fill_credit_specification) + d.block("placement", "Placement", self.fill_placement) + d.block("network_interfaces", "NetworkInterfaces", self.fill_interface) + d.block("tag_specifications", "TagSpecifications", self.fill_tag_specification) + + def fill_iam_instance_profile(self, i: Props) -> None: + """The iam_instance_profile block.""" + i.attrs({"arn": "Arn", "name": "Name"}) + + def fill_device(self, r: Props) -> None: + """One block_device_mappings block.""" + r.attrs({"device_name": "DeviceName", "virtual_name": "VirtualName"}) + # CloudFormation omits the device whenever NoDevice is present, usually as "". The + # provider ignores an empty no_device, so any value becomes a non-empty one. + no_device = r.take("NoDevice") + if no_device is not None: + r.set("no_device", self.no_device(r, no_device)) + r.block("ebs", "Ebs", self.fill_ebs) + + def no_device(self, r: Props, value: Any) -> Any: + """NoDevice as a value the provider acts on: never empty.""" + if isinstance(value, str): + return value or "true" + return Raw(f'coalesce({hcl.inline(r.ctx.expr(value))}, "true")') + + def fill_ebs(self, e: Props) -> None: + """The ebs block of a device.""" + ebs_items(e, with_snapshot=True) + + def fill_metadata_options(self, m: Props) -> None: + """The metadata_options block.""" + m.attrs( + { + "http_tokens": "HttpTokens", + "http_endpoint": "HttpEndpoint", + "instance_metadata_tags": "InstanceMetadataTags", + "http_protocol_ipv6": "HttpProtocolIpv6", + } + ) + m.number("http_put_response_hop_limit", "HttpPutResponseHopLimit") + + def fill_monitoring(self, m: Props) -> None: + """The monitoring block.""" + m.boolean("enabled", "Enabled") + + def fill_credit_specification(self, c: Props) -> None: + """The credit_specification block.""" + c.attr("cpu_credits", "CpuCredits") + + def fill_placement(self, c: Props) -> None: + """The placement block.""" + c.attrs( + { + "availability_zone": "AvailabilityZone", + "group_name": "GroupName", + "tenancy": "Tenancy", + } + ) + + def fill_interface(self, r: Props) -> None: + """One network_interfaces block.""" + r.boolean("associate_public_ip_address", "AssociatePublicIpAddress") + r.boolean("delete_on_termination", "DeleteOnTermination") + r.number("device_index", "DeviceIndex") + r.attrs( + { + "subnet_id": "SubnetId", + "description": "Description", + "private_ip_address": "PrivateIpAddress", + "network_interface_id": "NetworkInterfaceId", + "interface_type": "InterfaceType", + } + ) + r.list_attr("security_groups", "Groups") + + def fill_tag_specification(self, t: Props) -> None: + """One tag_specifications block.""" + t.attr("resource_type", "ResourceType") + t.tags() + + +# --- ECS -------------------------------------------------------------------------------- + + +def fill_strategy(r: Props) -> None: + """One capacity provider strategy item, of a cluster or a service.""" + r.attr("capacity_provider", "CapacityProvider") + r.number("weight", "Weight") + r.number("base", "Base") + + +def fill_placement_constraint(c: Props) -> None: + """One placement_constraints block, of a task definition or a service.""" + c.attrs({"type": "Type", "expression": "Expression"}) + + +class ServiceConnectDefaults: + """Fills the service_connect_defaults block of one cluster.""" + + def __init__(self, b: Builder) -> None: + """The defaults of the cluster `b` builds.""" + self.b = b + + def fill(self, s: Props) -> None: + """The service_connect_defaults block.""" + s.attr("namespace", "Namespace", self.namespace) + + def namespace(self, value: Any) -> Any: + """The namespace, which Terraform takes as an ARN.""" + b = self.b + if isinstance(value, str) and not value.startswith("arn:"): + b.ctx.note( + f"{b.logical_id}: ServiceConnectDefaults.Namespace '{value}' is a namespace name, " + "which CloudFormation looks up (or creates); Terraform needs the namespace ARN, " + "e.g. from an aws_service_discovery_http_namespace" + ) + return b.ctx.expr(value) + + +class EcsCluster(ResourceConverter): + """AWS::ECS::Cluster as aws_ecs_cluster, with its capacity providers as a separate + resource.""" + + cfn_type = "AWS::ECS::Cluster" + tf_type = "aws_ecs_cluster" + ref = "name" + attrs = {"Arn": "arn"} + import_id = "ClusterName" + + def convert(self, b: Builder) -> None: + """The cluster, then its capacity providers.""" + p = b.props + b.name_attr("name", "ClusterName") + p.block("setting", "ClusterSettings", self.fill_setting) + p.block( + "service_connect_defaults", "ServiceConnectDefaults", ServiceConnectDefaults(b).fill + ) + p.block("configuration", "Configuration", self.fill_configuration) + p.tags() + providers = p.take("CapacityProviders") + strategy = p.take("DefaultCapacityProviderStrategy") + if providers is None and strategy is None: + return + # Capacity providers are a separate resource in Terraform. + holder = Props(b.ctx, {}, b.logical_id, p.owner) + holder.set("cluster_name", b.self_ref("name")) + if providers is not None: + holder.set("capacity_providers", b.ctx.expr(providers)) + holder.add_blocks( + "default_capacity_provider_strategy", + strategy or [], + fill_strategy, + f"{b.logical_id}.DefaultCapacityProviderStrategy", + ) + b.add_resource("aws_ecs_cluster_capacity_providers", "_capacity_providers", holder.items) + + def fill_setting(self, s: Props) -> None: + """One setting block.""" + s.attrs({"name": "Name", "value": "Value"}) + + def fill_configuration(self, r: Props) -> None: + """The configuration block.""" + r.block( + "execute_command_configuration", + "ExecuteCommandConfiguration", + self.fill_execute_command, + ) + r.block( + "managed_storage_configuration", + "ManagedStorageConfiguration", + self.fill_managed_storage, + ) + + def fill_execute_command(self, e: Props) -> None: + """The execute_command_configuration block.""" + e.attrs({"kms_key_id": "KmsKeyId", "logging": "Logging"}) + e.block("log_configuration", "LogConfiguration", self.fill_exec_log_configuration) + + def fill_exec_log_configuration(self, r: Props) -> None: + """Where the execute command logs go.""" + r.boolean("cloud_watch_encryption_enabled", "CloudWatchEncryptionEnabled") + r.attr("cloud_watch_log_group_name", "CloudWatchLogGroupName") + r.boolean("s3_bucket_encryption_enabled", "S3EncryptionEnabled") + r.attr("s3_bucket_name", "S3BucketName") + r.attr("s3_key_prefix", "S3KeyPrefix") + + def fill_managed_storage(self, m: Props) -> None: + """The managed_storage_configuration block.""" + m.attrs( + { + "kms_key_id": "KmsKeyId", + "fargate_ephemeral_storage_kms_key_id": "FargateEphemeralStorageKmsKeyId", + } + ) + + +def if_branches(value: Any, convert: Callable[[Any], Any]) -> Any: + """`convert(value)`, or for `!If [C, a, b]` the same with a and b converted. Other + intrinsic functions are left as written.""" + if isinstance(value, dict) and intrinsic_name(value) is not None: + args = value[intrinsic_name(value)] + if intrinsic_name(value) == "Fn::If" and isinstance(args, list) and len(args) == 3: + name, yes, no = args + return {"Fn::If": [name, if_branches(yes, convert), if_branches(no, convert)]} + return value + return convert(value) + + +def string_value(value: Any) -> Any: + """A literal as the text CloudFormation would pass: true -> "true", 8080 -> "8080".""" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int | float): + return str(value) + return value + + +class ContainerField: + """Turns the text value of one container definition field into the number or boolean + the field takes.""" + + numbers: ClassVar[frozenset[str]] = frozenset( + { + "cpu", + "memory", + "memoryReservation", + "containerPort", + "hostPort", + "startTimeout", + "stopTimeout", + "softLimit", + "hardLimit", + "interval", + "timeout", + "retries", + "startPeriod", + "sharedMemorySize", + "maxSwap", + "swappiness", + "size", + } + ) + booleans: ClassVar[frozenset[str]] = frozenset( + { + "essential", + "readOnly", + "privileged", + "readonlyRootFilesystem", + "disableNetworking", + "interactive", + "pseudoTerminal", + "initProcessEnabled", + } + ) + digits: ClassVar[re.Pattern[str]] = re.compile(r"^[0-9]+$") + + def __init__(self, camel: str) -> None: + """The field named `camel` ("containerPort").""" + self.camel = camel + + def typed(self, item: Any) -> Any: + """`item`, with digits as a number and "true"/"false" as a boolean where the field + takes one.""" + if self.camel in self.numbers and isinstance(item, str) and self.digits.match(item): + return int(item) + is_text = isinstance(item, str) + if self.camel in self.booleans and is_text and item.lower() in ("true", "false"): + return item.lower() == "true" + return item + + +class ContainerDefinitions: + """CloudFormation container definitions (PascalCase) as the JSON the ECS API takes + (camelCase). Intrinsic functions and user maps are left as written, but both branches of + an Fn::If are converted too. Numbers and booleans written as strings become real ones, + as ECS rejects "256" for cpu, and the string fields CloudFormation coerces (environment + values, labels, log options) become strings, as ECS rejects 8080 for them.""" + + # Container definition keys holding user maps: their own keys stay as written. + maps: ClassVar[frozenset[str]] = frozenset({"DockerLabels", "Options", "DriverOpts", "Labels"}) + + def convert(self, value: Any) -> Any: + """The ECS API form of `value`, a container definition or part of one.""" + if isinstance(value, list): + return [self.convert(item) for item in value] + if not isinstance(value, dict): + return value + if intrinsic_name(value) is not None: + return if_branches(value, self.convert) + result: dict[str, Any] = {} + for name, item in value.items(): + key = str(name) + camel = key[:1].lower() + key[1:] + if key in self.maps: + result[camel] = if_branches(item, self.string_values) + continue + converted = self.convert(item) + if camel == "environment": + converted = if_branches(converted, self.environment) + result[camel] = if_branches(converted, ContainerField(camel).typed) + return result + + def string_values(self, value: Any) -> Any: + """A user map with every value as text.""" + if not isinstance(value, dict): + return value + return {k: if_branches(v, string_value) for k, v in value.items()} + + def environment(self, value: Any) -> Any: + """The environment list with every value as text.""" + if not isinstance(value, list): + return value + return [if_branches(entry, self.environment_entry) for entry in value] + + def environment_entry(self, entry: Any) -> Any: + """One environment entry with its value as text.""" + if not isinstance(entry, dict) or "value" not in entry: + return entry + return dict(entry, value=if_branches(entry["value"], string_value)) + + +class EcsTaskDefinition(ResourceConverter): + """AWS::ECS::TaskDefinition as aws_ecs_task_definition.""" + + cfn_type = "AWS::ECS::TaskDefinition" + tf_type = "aws_ecs_task_definition" + ref = "arn" + attrs = {"TaskDefinitionArn": "arn"} + + def convert(self, b: Builder) -> None: + """The task definition, its containers and volumes.""" + p = b.props + b.name_attr("family", "Family") + definitions = p.take("ContainerDefinitions") + if definitions is not None: + container_json = ContainerDefinitions().convert(definitions) + p.set("container_definitions", Call("jsonencode", b.ctx.expr(container_json))) + p.attrs( + { + "cpu": "Cpu", + "memory": "Memory", + "network_mode": "NetworkMode", + "execution_role_arn": "ExecutionRoleArn", + "task_role_arn": "TaskRoleArn", + "pid_mode": "PidMode", + "ipc_mode": "IpcMode", + } + ) + p.list_attr("requires_compatibilities", "RequiresCompatibilities") + p.boolean("enable_fault_injection", "EnableFaultInjection") + p.block("runtime_platform", "RuntimePlatform", self.fill_runtime_platform) + p.block("ephemeral_storage", "EphemeralStorage", self.fill_ephemeral_storage) + p.block("placement_constraints", "PlacementConstraints", fill_placement_constraint) + p.block("volume", "Volumes", self.fill_volume) + p.tags() + + def fill_runtime_platform(self, r: Props) -> None: + """The runtime_platform block.""" + r.attrs( + { + "cpu_architecture": "CpuArchitecture", + "operating_system_family": "OperatingSystemFamily", + } + ) + + def fill_ephemeral_storage(self, e: Props) -> None: + """The ephemeral_storage block.""" + e.number("size_in_gib", "SizeInGiB") + + def fill_volume(self, r: Props) -> None: + """One volume block.""" + r.attr("name", "Name") + r.boolean("configure_at_launch", "ConfigureAtLaunch") + when, host = r.ctx.optional_item(r.take("Host")) + host = r.literal("Host", dict, value=host) + if host is not None and host.get("SourcePath") is not None: + path = r.ctx.expr(host["SourcePath"]) + if when is not None: + path = Raw(f"{when} ? {wrap_operand(hcl.inline(path))} : null") + r.set("host_path", path) + r.block("efs_volume_configuration", "EFSVolumeConfiguration", self.fill_efs_volume) + r.block( + "docker_volume_configuration", + "DockerVolumeConfiguration", + self.fill_docker_volume, + ) + + def fill_efs_volume(self, e: Props) -> None: + """The efs_volume_configuration block.""" + e.attrs( + { + "file_system_id": "FilesystemId", + "root_directory": "RootDirectory", + "transit_encryption": "TransitEncryption", + } + ) + e.number("transit_encryption_port", "TransitEncryptionPort") + e.block("authorization_config", "AuthorizationConfig", self.fill_efs_authorization) + + def fill_efs_authorization(self, a: Props) -> None: + """The authorization_config block of an EFS volume.""" + a.attrs({"access_point_id": "AccessPointId", "iam": "IAM"}) + + def fill_docker_volume(self, d: Props) -> None: + """The docker_volume_configuration block.""" + d.boolean("autoprovision", "Autoprovision") + d.attrs( + { + "driver": "Driver", + "scope": "Scope", + "driver_opts": "DriverOpts", + "labels": "Labels", + } + ) + + +class EcsService(ResourceConverter): + """AWS::ECS::Service as aws_ecs_service.""" + + cfn_type = "AWS::ECS::Service" + tf_type = "aws_ecs_service" + attrs = {"Name": "name", "ServiceArn": "arn"} + + def convert(self, b: Builder) -> None: + """The service, its deployment, network and load balancer settings.""" + p = b.props + b.name_attr("name", "ServiceName") + p.attrs( + { + "cluster": "Cluster", + "task_definition": "TaskDefinition", + "launch_type": "LaunchType", + "platform_version": "PlatformVersion", + "scheduling_strategy": "SchedulingStrategy", + "propagate_tags": "PropagateTags", + "iam_role": "Role", + } + ) + if not p.number("desired_count", "DesiredCount"): + self.default_desired_count(b, p) + p.number("health_check_grace_period_seconds", "HealthCheckGracePeriodSeconds") + p.boolean("enable_execute_command", "EnableExecuteCommand") + p.boolean("enable_ecs_managed_tags", "EnableECSManagedTags") + self.deployment(b, p) + network = p.take("NetworkConfiguration") + if network is not None: + inner = Props(b.ctx, network, f"{b.logical_id}.NetworkConfiguration", p.owner) + inner.block("network_configuration", "AwsvpcConfiguration", self.fill_awsvpc) + inner.finish() + p.items.extend(inner.items) + p.block("load_balancer", "LoadBalancers", self.fill_load_balancer) + p.block("deployment_controller", "DeploymentController", self.fill_deployment_controller) + p.block("capacity_provider_strategy", "CapacityProviderStrategy", fill_strategy) + p.block("placement_constraints", "PlacementConstraints", fill_placement_constraint) + p.block("ordered_placement_strategy", "PlacementStrategies", self.fill_placement_strategy) + p.block("service_registries", "ServiceRegistries", self.fill_service_registry) + p.tags() + + def default_desired_count(self, b: Builder, p: Props) -> None: + """CloudFormation starts one task when DesiredCount is left out (except for DAEMON + services, which take none); the Terraform default is 0.""" + strategy = (b.resource.get("Properties") or {}).get("SchedulingStrategy") + if strategy is None or b.ctx.is_no_value(strategy): + p.set("desired_count", 1) + elif isinstance(strategy, str): + if strategy.upper() != "DAEMON": + p.set("desired_count", 1) + else: + strategy_text = wrap_operand(hcl.inline(b.ctx.expr(strategy))) + p.set("desired_count", Raw(f'{strategy_text} == "DAEMON" ? null : 1')) + + def deployment(self, b: Builder, p: Props) -> None: + """DeploymentConfiguration, whose parts are arguments and blocks of the service in + Terraform.""" + deployment = p.take("DeploymentConfiguration") + if deployment is None: + return + inner = Props(b.ctx, deployment, f"{b.logical_id}.DeploymentConfiguration", p.owner) + inner.number("deployment_maximum_percent", "MaximumPercent") + inner.number("deployment_minimum_healthy_percent", "MinimumHealthyPercent") + inner.block( + "deployment_circuit_breaker", "DeploymentCircuitBreaker", self.fill_circuit_breaker + ) + inner.block("alarms", "Alarms", self.fill_alarms) + inner.finish() + p.items.extend(inner.items) + + def fill_circuit_breaker(self, c: Props) -> None: + """The deployment_circuit_breaker block.""" + c.boolean("enable", "Enable") + c.boolean("rollback", "Rollback") + + def fill_alarms(self, a: Props) -> None: + """The alarms block.""" + a.list_attr("alarm_names", "AlarmNames") + a.boolean("enable", "Enable") + a.boolean("rollback", "Rollback") + + def fill_awsvpc(self, r: Props) -> None: + """The network_configuration block.""" + r.list_attr("subnets", "Subnets") + r.list_attr("security_groups", "SecurityGroups") + value = r.take("AssignPublicIp") + if value is None: + return + if isinstance(value, str) and value.upper() in ("ENABLED", "DISABLED"): + r.set("assign_public_ip", value.upper() == "ENABLED") + else: + operand = wrap_operand(hcl.inline(r.ctx.expr(value))) + r.set("assign_public_ip", Raw(f'{operand} == "ENABLED"')) + + def fill_load_balancer(self, lb: Props) -> None: + """One load_balancer block.""" + lb.attrs( + { + "container_name": "ContainerName", + "target_group_arn": "TargetGroupArn", + "elb_name": "LoadBalancerName", + } + ) + lb.number("container_port", "ContainerPort") + + def fill_deployment_controller(self, d: Props) -> None: + """The deployment_controller block.""" + d.attr("type", "Type") + + def fill_placement_strategy(self, s: Props) -> None: + """One ordered_placement_strategy block.""" + s.attrs({"type": "Type", "field": "Field"}) + + def fill_service_registry(self, s: Props) -> None: + """The service_registries block.""" + s.attrs({"registry_arn": "RegistryArn", "container_name": "ContainerName"}) + s.number("port", "Port") + s.number("container_port", "ContainerPort") + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + LambdaFunction, + LambdaPermission, + LambdaEventSourceMapping, + LambdaLayerVersion, + LambdaUrl, + LambdaAlias, + LambdaVersion, + Ec2Instance, + Ec2LaunchTemplate, + EcsCluster, + EcsTaskDefinition, + EcsService, +) diff --git a/services/converter-api/converters/cfn/resources/data.py b/services/converter-api/converters/cfn/resources/data.py new file mode 100644 index 0000000..a87a0c8 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/data.py @@ -0,0 +1,461 @@ +"""RDS, KMS, Secrets Manager and SSM Parameter Store.""" + +from __future__ import annotations + +from typing import Any + +from converters.cfn import hcl +from converters.cfn.builder import Builder, Props +from converters.cfn.expressions import intrinsic_name +from converters.cfn.models import Attr, Block, Raw, ResourceInfo +from converters.cfn.naming import identifier +from converters.cfn.resources.base import ResourceConverter + +# --- RDS -------------------------------------------------------------------------------- + + +def _lowercase(b: Builder, tf_name: str, cfn_name: str) -> None: + """A name RDS stores in lowercase. CloudFormation lowercases it; the provider rejects + uppercase letters, so a literal is lowercased and an expression goes through lower(). + References to resources of the template are already lowercase.""" + value = b.props.take(cfn_name) + if value is None: + return + if isinstance(value, str): + b.props.set(tf_name, value.lower()) + return + if isinstance(value, dict) and ("Fn::GetAtt" in value or value.get("Ref") in b.ctx.resources): + b.props.set(tf_name, b.ctx.expr(value)) + return + b.props.set(tf_name, Raw(f"lower({hcl.inline(b.ctx.expr(value))})")) + + +def _apply_immediately(b: Builder) -> None: + """CloudFormation applies DB instance changes at once (ApplyImmediately defaults to + true); Terraform waits for the maintenance window unless told otherwise.""" + if not b.props.boolean("apply_immediately", "ApplyImmediately"): + b.props.set("apply_immediately", True) + + +def _final_snapshot(b: Builder, identifier_prop: str) -> list[Attr]: + """CloudFormation snapshots DB instances and clusters on delete unless DeletionPolicy is + Delete. The Terraform default is the opposite, so spell it out. Call before the identifier + property is taken; add the returned attributes at the end.""" + if b.resource.get("DeletionPolicy") == "Delete": + return [Attr("skip_final_snapshot", True)] + name = b.props.peek(identifier_prop) + base = name.lower() if isinstance(name, str) else identifier(b.logical_id).replace("_", "-") + if b.resource.get("DeletionPolicy") is None: + b.ctx.note( + f"{b.logical_id}: CloudFormation snapshots this database on delete by default; " + f"Terraform does the same here, naming the snapshot '{base}-final-snapshot'" + ) + return [ + Attr("skip_final_snapshot", False), + Attr("final_snapshot_identifier", f"{base}-final-snapshot"), + ] + + +def _password(b: Builder, tf_name: str) -> None: + """MasterUserPassword as `tf_name`, with a note on where the password ends up.""" + if b.props.attr(tf_name, "MasterUserPassword"): + b.ctx.note( + f"{b.logical_id}: the master password ends up in the Terraform state; prefer " + "manage_master_user_password = true (a Secrets Manager secret) or a write-only " + f"{tf_name}_wo argument" + ) + + +def _master_secret(b: Builder) -> None: + """The KMS key of MasterUserSecret as master_user_secret_kms_key_id.""" + secret = b.props.take("MasterUserSecret") + if isinstance(secret, dict) and secret.get("KmsKeyId") is not None: + b.props.set("master_user_secret_kms_key_id", b.ctx.expr(secret["KmsKeyId"])) + + +def _parameter_value(b: Builder, value: Any) -> Any: + """Parameter values are text; CloudFormation writes booleans as "true" and "false".""" + if isinstance(value, dict): + return b.ctx.expr(value) + if isinstance(value, bool): + return "true" if value else "false" + return str(value) + + +class DbInstance(ResourceConverter): + """AWS::RDS::DBInstance as aws_db_instance, or as aws_rds_cluster_instance for a member + of a cluster.""" + + cfn_type = "AWS::RDS::DBInstance" + tf_type = "aws_db_instance" + ref = "identifier" + attrs = { + "Endpoint.Address": "address", + "Endpoint.Port": "port", + "Endpoint.HostedZoneId": "hosted_zone_id", + "DBInstanceArn": "arn", + "DbiResourceId": "resource_id", + "MasterUserSecret.SecretArn": "master_user_secret[0].secret_arn", + } + import_id = "DBInstanceIdentifier" + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """A DB instance of an Aurora (or Multi-AZ) cluster is an aws_rds_cluster_instance.""" + if (resource.get("Properties") or {}).get("DBClusterIdentifier") is not None: + info.tf_type = "aws_rds_cluster_instance" + info.attrs.update( + { + "Endpoint.Address": "endpoint", + "DbiResourceId": "dbi_resource_id", + } + ) + info.attrs.pop("Endpoint.HostedZoneId") + info.attrs.pop("MasterUserSecret.SecretArn") + + def convert(self, b: Builder) -> None: + """A standalone instance with the snapshot and apply settings of CloudFormation. A + cluster member goes to convert_cluster_instance.""" + if b.info.tf_type == "aws_rds_cluster_instance": + self.convert_cluster_instance(b) + return + p = b.props + snapshot = _final_snapshot(b, "DBInstanceIdentifier") + _lowercase(b, "identifier", "DBInstanceIdentifier") + p.attrs( + { + "engine": "Engine", + "engine_version": "EngineVersion", + "instance_class": "DBInstanceClass", + "storage_type": "StorageType", + "kms_key_id": "KmsKeyId", + "username": "MasterUsername", + "db_name": "DBName", + "db_subnet_group_name": "DBSubnetGroupName", + "parameter_group_name": "DBParameterGroupName", + "option_group_name": "OptionGroupName", + "backup_window": "PreferredBackupWindow", + "maintenance_window": "PreferredMaintenanceWindow", + "performance_insights_kms_key_id": "PerformanceInsightsKMSKeyId", + "monitoring_role_arn": "MonitoringRoleArn", + "availability_zone": "AvailabilityZone", + "ca_cert_identifier": "CACertificateIdentifier", + "license_model": "LicenseModel", + "snapshot_identifier": "DBSnapshotIdentifier", + "replicate_source_db": "SourceDBInstanceIdentifier", + "network_type": "NetworkType", + "character_set_name": "CharacterSetName", + "timezone": "Timezone", + } + ) + for tf_name, cfn_name in ( + ("allocated_storage", "AllocatedStorage"), + ("max_allocated_storage", "MaxAllocatedStorage"), + ("iops", "Iops"), + ("storage_throughput", "StorageThroughput"), + ("port", "Port"), + ("backup_retention_period", "BackupRetentionPeriod"), + ("monitoring_interval", "MonitoringInterval"), + ("performance_insights_retention_period", "PerformanceInsightsRetentionPeriod"), + ): + p.number(tf_name, cfn_name) + for tf_name, cfn_name in ( + ("storage_encrypted", "StorageEncrypted"), + ("multi_az", "MultiAZ"), + ("publicly_accessible", "PubliclyAccessible"), + ("deletion_protection", "DeletionProtection"), + ("auto_minor_version_upgrade", "AutoMinorVersionUpgrade"), + ("allow_major_version_upgrade", "AllowMajorVersionUpgrade"), + ("copy_tags_to_snapshot", "CopyTagsToSnapshot"), + ("iam_database_authentication_enabled", "EnableIAMDatabaseAuthentication"), + ("performance_insights_enabled", "EnablePerformanceInsights"), + ("manage_master_user_password", "ManageMasterUserPassword"), + ("delete_automated_backups", "DeleteAutomatedBackups"), + ): + p.boolean(tf_name, cfn_name) + _password(b, "password") + _master_secret(b) + p.list_attr("vpc_security_group_ids", "VPCSecurityGroups") + p.list_attr("enabled_cloudwatch_logs_exports", "EnableCloudwatchLogsExports") + _apply_immediately(b) + p.items.extend(snapshot) + p.tags() + + def convert_cluster_instance(self, b: Builder) -> None: + """A cluster member. CloudFormation takes no snapshot of it on delete (the cluster holds + the data), so there are no final snapshot settings.""" + p = b.props + _lowercase(b, "identifier", "DBInstanceIdentifier") + p.attrs( + { + "cluster_identifier": "DBClusterIdentifier", + "engine": "Engine", + "engine_version": "EngineVersion", + "instance_class": "DBInstanceClass", + "db_subnet_group_name": "DBSubnetGroupName", + "db_parameter_group_name": "DBParameterGroupName", + "availability_zone": "AvailabilityZone", + "ca_cert_identifier": "CACertificateIdentifier", + "monitoring_role_arn": "MonitoringRoleArn", + "performance_insights_kms_key_id": "PerformanceInsightsKMSKeyId", + "preferred_backup_window": "PreferredBackupWindow", + "preferred_maintenance_window": "PreferredMaintenanceWindow", + } + ) + for tf_name, cfn_name in ( + ("monitoring_interval", "MonitoringInterval"), + ("performance_insights_retention_period", "PerformanceInsightsRetentionPeriod"), + ("promotion_tier", "PromotionTier"), + ): + p.number(tf_name, cfn_name) + for tf_name, cfn_name in ( + ("publicly_accessible", "PubliclyAccessible"), + ("auto_minor_version_upgrade", "AutoMinorVersionUpgrade"), + ("copy_tags_to_snapshot", "CopyTagsToSnapshot"), + ("performance_insights_enabled", "EnablePerformanceInsights"), + ): + p.boolean(tf_name, cfn_name) + _apply_immediately(b) + p.tags() + + +class DbSubnetGroup(ResourceConverter): + """AWS::RDS::DBSubnetGroup as aws_db_subnet_group.""" + + cfn_type = "AWS::RDS::DBSubnetGroup" + tf_type = "aws_db_subnet_group" + ref = "name" + import_id = "DBSubnetGroupName" + + def convert(self, b: Builder) -> None: + """The subnet group settings.""" + p = b.props + _lowercase(b, "name", "DBSubnetGroupName") + p.attr("description", "DBSubnetGroupDescription") + p.list_attr("subnet_ids", "SubnetIds") + p.tags() + + +class DbParameterGroup(ResourceConverter): + """AWS::RDS::DBParameterGroup as aws_db_parameter_group.""" + + cfn_type = "AWS::RDS::DBParameterGroup" + tf_type = "aws_db_parameter_group" + ref = "name" + import_id = "DBParameterGroupName" + + def convert(self, b: Builder) -> None: + """The parameter group, with one parameter block per parameter.""" + p = b.props + _lowercase(b, "name", "DBParameterGroupName") + p.attr("description", "Description") + p.attr("family", "Family") + parameters = p.peek("Parameters") + if isinstance(parameters, dict) and intrinsic_name(parameters) is None: + p.drop("Parameters") + for name, value in parameters.items(): + # No apply_method: like CloudFormation, the provider applies each parameter the + # default way, immediately ("pending-reboot" would hold dynamic ones back). + items = [Attr("name", str(name)), Attr("value", _parameter_value(b, value))] + p.items.append(Block("parameter", [], items)) + if parameters: + b.ctx.note( + f"{b.logical_id}: the provider applies parameters immediately; a static " + 'parameter fails that way and needs apply_method = "pending-reboot" (it ' + "takes effect at the next reboot, as with CloudFormation)" + ) + p.tags() + + +class DbCluster(ResourceConverter): + """AWS::RDS::DBCluster as aws_rds_cluster.""" + + cfn_type = "AWS::RDS::DBCluster" + tf_type = "aws_rds_cluster" + ref = "cluster_identifier" + attrs = { + "Endpoint.Address": "endpoint", + "Endpoint.Port": "port", + "ReadEndpoint.Address": "reader_endpoint", + "DBClusterArn": "arn", + "DBClusterResourceId": "cluster_resource_id", + "MasterUserSecret.SecretArn": "master_user_secret[0].secret_arn", + } + import_id = "DBClusterIdentifier" + + def convert(self, b: Builder) -> None: + """The cluster, with the snapshot settings of CloudFormation.""" + p = b.props + snapshot = _final_snapshot(b, "DBClusterIdentifier") + _lowercase(b, "cluster_identifier", "DBClusterIdentifier") + p.attrs( + { + "engine": "Engine", + "engine_version": "EngineVersion", + "engine_mode": "EngineMode", + "database_name": "DatabaseName", + "master_username": "MasterUsername", + "db_subnet_group_name": "DBSubnetGroupName", + "db_cluster_parameter_group_name": "DBClusterParameterGroupName", + "db_cluster_instance_class": "DBClusterInstanceClass", + "preferred_backup_window": "PreferredBackupWindow", + "preferred_maintenance_window": "PreferredMaintenanceWindow", + "kms_key_id": "KmsKeyId", + "storage_type": "StorageType", + "network_type": "NetworkType", + "snapshot_identifier": "SnapshotIdentifier", + } + ) + for tf_name, cfn_name in ( + ("port", "Port"), + ("backup_retention_period", "BackupRetentionPeriod"), + ("allocated_storage", "AllocatedStorage"), + ("iops", "Iops"), + ): + p.number(tf_name, cfn_name) + for tf_name, cfn_name in ( + ("storage_encrypted", "StorageEncrypted"), + ("deletion_protection", "DeletionProtection"), + ("iam_database_authentication_enabled", "EnableIAMDatabaseAuthentication"), + ("enable_http_endpoint", "EnableHttpEndpoint"), + ("copy_tags_to_snapshot", "CopyTagsToSnapshot"), + ("manage_master_user_password", "ManageMasterUserPassword"), + ): + p.boolean(tf_name, cfn_name) + _password(b, "master_password") + _master_secret(b) + p.list_attr("vpc_security_group_ids", "VpcSecurityGroupIds") + p.list_attr("enabled_cloudwatch_logs_exports", "EnableCloudwatchLogsExports") + p.block( + "serverlessv2_scaling_configuration", + "ServerlessV2ScalingConfiguration", + self.fill_scaling_v2, + ) + p.items.extend(snapshot) + p.tags() + + def fill_scaling_v2(self, s: Props) -> None: + """The serverlessv2_scaling_configuration block.""" + s.number("min_capacity", "MinCapacity") + s.number("max_capacity", "MaxCapacity") + s.number("seconds_until_auto_pause", "SecondsUntilAutoPause") + + +# --- KMS -------------------------------------------------------------------------------- + + +class KmsKey(ResourceConverter): + """AWS::KMS::Key as aws_kms_key.""" + + cfn_type = "AWS::KMS::Key" + tf_type = "aws_kms_key" + ref = "key_id" + attrs = {"Arn": "arn", "KeyId": "key_id"} + + def convert(self, b: Builder) -> None: + """The key settings and its key policy.""" + p = b.props + p.attr("description", "Description") + p.json("policy", "KeyPolicy") + p.boolean("enable_key_rotation", "EnableKeyRotation") + p.boolean("is_enabled", "Enabled") + p.attr("customer_master_key_spec", "KeySpec") + p.attr("key_usage", "KeyUsage") + p.boolean("multi_region", "MultiRegion") + p.number("deletion_window_in_days", "PendingWindowInDays") + p.number("rotation_period_in_days", "RotationPeriodInDays") + p.boolean("bypass_policy_lockout_safety_check", "BypassPolicyLockoutSafetyCheck") + p.tags() + + +class KmsAlias(ResourceConverter): + """AWS::KMS::Alias as aws_kms_alias.""" + + cfn_type = "AWS::KMS::Alias" + tf_type = "aws_kms_alias" + ref = "name" + import_id = "AliasName" + + def convert(self, b: Builder) -> None: + """The alias name and its key.""" + b.props.attr("name", "AliasName") + b.props.attr("target_key_id", "TargetKeyId") + + +# --- Secrets Manager -------------------------------------------------------------------- + + +class SecretsManagerSecret(ResourceConverter): + """AWS::SecretsManager::Secret as aws_secretsmanager_secret, with its value as a + separate aws_secretsmanager_secret_version.""" + + cfn_type = "AWS::SecretsManager::Secret" + tf_type = "aws_secretsmanager_secret" + ref = "arn" + attrs = {"Id": "id"} + + def convert(self, b: Builder) -> None: + """The secret, its replicas and its value.""" + p = b.props + p.attr("name", "Name") + p.attr("description", "Description") + p.attr("kms_key_id", "KmsKeyId") + p.block("replica", "ReplicaRegions", self.fill_replica) + p.tags() + value = p.take("SecretString") + if value is not None: + b.add_resource( + "aws_secretsmanager_secret_version", + "_value", + [Attr("secret_id", b.self_ref("id")), Attr("secret_string", b.ctx.expr(value))], + ) + b.ctx.note( + f"{b.logical_id}: the secret value ends up in the Terraform state; consider the " + "write-only secret_string_wo argument" + ) + if p.has("GenerateSecretString"): + b.ctx.note( + f"{b.logical_id}: GenerateSecretString has no aws provider equivalent; generate " + "the value with an ephemeral random_password and secret_string_wo or convert " + "this secret with the awscc provider" + ) + + def fill_replica(self, r: Props) -> None: + """One replica block.""" + r.attrs({"region": "Region", "kms_key_id": "KmsKeyId"}) + + +# --- SSM Parameter Store ---------------------------------------------------------------- + + +class SsmParameter(ResourceConverter): + """AWS::SSM::Parameter as aws_ssm_parameter.""" + + cfn_type = "AWS::SSM::Parameter" + tf_type = "aws_ssm_parameter" + ref = "name" + attrs = {"Type": "type", "Value": "value"} + import_id = "Name" + + def convert(self, b: Builder) -> None: + """The parameter settings.""" + p = b.props + b.name_attr("name", "Name") + p.attr("type", "Type") + p.attr("value", "Value") + p.attr("description", "Description") + p.attr("allowed_pattern", "AllowedPattern") + p.attr("tier", "Tier") + p.attr("data_type", "DataType") + p.tags() + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + DbInstance, + DbSubnetGroup, + DbParameterGroup, + DbCluster, + KmsKey, + KmsAlias, + SecretsManagerSecret, + SsmParameter, +) diff --git a/services/converter-api/converters/cfn/resources/iam.py b/services/converter-api/converters/cfn/resources/iam.py new file mode 100644 index 0000000..bdf9d83 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/iam.py @@ -0,0 +1,316 @@ +"""IAM: roles, policies, instance profiles, users and groups. + +Inline policies and managed policy attachments become separate resources +(aws_iam_role_policy, aws_iam_role_policy_attachment...): the provider deprecated the +inline_policy and managed_policy_arns arguments. +""" + +from __future__ import annotations + +from typing import Any + +from converters.cfn.builder import Builder, snippet +from converters.cfn.expressions import NO_VALUE, intrinsic_name +from converters.cfn.models import Attr, Raw, ResourceInfo +from converters.cfn.naming import UniqueNames, identifier +from converters.cfn.resources.base import ResourceConverter +from converters.cfn.resources.messaging import main_index, optional + +# kind -> (inline policy type, attachment type, argument naming the principal) +_PRINCIPALS = { + "role": ("aws_iam_role_policy", "aws_iam_role_policy_attachment", "role"), + "user": ("aws_iam_user_policy", "aws_iam_user_policy_attachment", "user"), + "group": ("aws_iam_group_policy", "aws_iam_group_policy_attachment", "group"), +} +# The properties of AWS::IAM::Policy and AWS::IAM::ManagedPolicy that list principals. +_TARGET_PROPS = (("role", "Roles"), ("user", "Users"), ("group", "Groups")) + + +def _literal_text(value: Any) -> str | None: + """The text of a literal string, a Fn::Sub template, or the literal parts of a Fn::Join + (the CDK writes managed policy ARNs that way), for naming.""" + if isinstance(value, str): + return value + if isinstance(value, dict) and intrinsic_name(value) == "Fn::Sub": + args = value["Fn::Sub"] + text = args[0] if isinstance(args, list) and args else args + return text if isinstance(text, str) else None + if isinstance(value, dict) and intrinsic_name(value) == "Fn::Join": + args = value["Fn::Join"] + if isinstance(args, list) and len(args) == 2 and isinstance(args[1], list): + text = "".join(part for part in args[1] if isinstance(part, str)) + return text or None + return None + + +def _target_name(value: Any) -> str | None: + """A readable name for a principal: its literal name or the referenced logical id.""" + if isinstance(value, dict) and intrinsic_name(value) == "Ref": + return str(value["Ref"]) + return _literal_text(value) + + +def _inline_policies(b: Builder, kind: str) -> None: + """Inline policies ([{PolicyName, PolicyDocument}]) of the role, user or group itself.""" + policies = b.props.take("Policies") + if policies is None: + return + tf_type, _, argument = _PRINCIPALS[kind] + suffixes = UniqueNames() + entries = policies if isinstance(policies, list) else [policies] + for index, item in enumerate(entries, 1): + if b.ctx.is_no_value(item): + continue + # An `!If [Cond, {...}, !Ref AWS::NoValue]` entry becomes a counted resource. + when, policy = b.ctx.optional_item(item) + if not isinstance(policy, dict) or intrinsic_name(policy) is not None: + b.ctx.note( + f"{b.logical_id}: inline policy {index} is computed by a function and was not " + f"converted; add it as a {tf_type} by hand" + ) + b.props.comment(f"Policies[{index - 1}] was not converted: {snippet(item)}") + continue + name = policy.get("PolicyName") + label = _literal_text(name) or f"policy_{index}" + suffix = suffixes.take("_" + identifier(label, f"policy_{index}")) + items: list[Any] = [Attr(argument, b.self_ref("name"))] + if name is not None: + items.insert(0, Attr("name", b.ctx.expr(name))) + items.append(Attr("policy", b.ctx.json(policy.get("PolicyDocument", {})))) + b.add_resource(tf_type, suffix, items, when=when) + + +def _managed_policies(b: Builder, kind: str) -> None: + """ManagedPolicyArns: one attachment each. Separate resources rather than for_each, so + ARNs of policies created in the same configuration leave the plan unblocked.""" + arns = b.props.take("ManagedPolicyArns") + if arns is None: + return + _, tf_type, argument = _PRINCIPALS[kind] + if not isinstance(arns, list): + b.ctx.note( + f"{b.logical_id}: ManagedPolicyArns is computed by a function and was not " + "converted; attach the policies by hand" + ) + b.props.comment(f"ManagedPolicyArns was not converted: {snippet(arns)}") + return + suffixes = UniqueNames() + for index, item in enumerate(arns, 1): + if b.ctx.is_no_value(item): + continue + when, arn = b.ctx.optional_item(item) + text = _literal_text(arn) + label = text.rsplit("/", 1)[-1] if text and "/" in text else f"policy_{index}" + suffix = suffixes.take("_" + identifier(label, f"policy_{index}")) + b.add_resource( + tf_type, + suffix, + [Attr(argument, b.self_ref("name")), Attr("policy_arn", b.ctx.expr(arn))], + when=when, + ) + + +def _policy_targets(resource: dict[str, Any]) -> list[tuple[str, Any]]: + """(kind, principal) for every role, user and group listed literally. A principal may be + `!If [Cond, x, !Ref AWS::NoValue]`: it then gets a counted resource.""" + properties = resource.get("Properties") or {} + targets: list[tuple[str, Any]] = [] + for kind, cfn_name in _TARGET_PROPS: + values = properties.get(cfn_name) + if isinstance(values, list): + targets.extend((kind, value) for value in values if value != NO_VALUE) + return targets + + +def _take_targets(b: Builder) -> None: + """Drop the principal lists that were expanded. A computed list is left for finish(), + which keeps it as a comment and reports it.""" + for _, cfn_name in _TARGET_PROPS: + if isinstance(b.props.peek(cfn_name), list): + b.props.drop(cfn_name) + + +class IamRole(ResourceConverter): + """AWS::IAM::Role as aws_iam_role, with its policies as separate resources.""" + + cfn_type = "AWS::IAM::Role" + tf_type = "aws_iam_role" + ref = "name" + attrs = {"Arn": "arn", "RoleId": "unique_id"} + import_id = "RoleName" + + def convert(self, b: Builder) -> None: + """The role, its inline policies and its managed policy attachments.""" + p = b.props + p.attr("name", "RoleName") + p.attr("description", "Description") + p.attr("path", "Path") + p.json("assume_role_policy", "AssumeRolePolicyDocument") + p.number("max_session_duration", "MaxSessionDuration") + p.attr("permissions_boundary", "PermissionsBoundary") + p.tags() + _inline_policies(b, "role") + _managed_policies(b, "role") + + +class IamPolicy(ResourceConverter): + """AWS::IAM::Policy as an inline policy of each listed role, user and group.""" + + cfn_type = "AWS::IAM::Policy" + tf_type = "aws_iam_role_policy" + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """The type of the main resource follows its principal (role, user or group): the + first one that is always there. When every principal is optional, the main resource + is counted.""" + targets = _policy_targets(resource) + if targets: + kind, principal = targets[main_index([value for _, value in targets])] + info.tf_type = _PRINCIPALS[kind][0] + if optional(principal): + info.conditional = True + + def convert(self, b: Builder) -> None: + """An inline policy for each listed role, user and group. The first principal that + is always there gets the main resource; each further one gets its own copy.""" + p = b.props + targets = _policy_targets(b.resource) + _take_targets(b) + name = p.take("PolicyName") + policy = b.ctx.json(p.take("PolicyDocument", {})) + principals: list[tuple[str, Any, str | None, str | None]] = [] + for kind, target in targets: + when, value = b.ctx.optional_item(target) + principals.append((kind, b.ctx.expr(value), _target_name(value), when)) + main = main_index([target for _, target in targets]) + if not principals: + variable = b.ctx.placeholder_variable( + f"{b.logical_id}_role", + f"Role that {b.logical_id} (AWS::IAM::Policy) is attached to", + ) + b.ctx.note( + f"{b.logical_id} lists no role, user or group Terraform can read; it is " + f"attached to {variable} instead" + ) + principals = [("role", Raw(variable), None, None)] + suffixes = UniqueNames() + for index, (kind, value, label, when) in enumerate(principals): + items: list[Any] = [Attr(_PRINCIPALS[kind][2], value), Attr("policy", policy)] + if name is not None: + items.insert(0, Attr("name", b.ctx.expr(name))) + if index == main: + p.items.extend(items) + continue + fallback = f"{kind}_{index + 1}" + suffix = suffixes.take("_" + identifier(label or fallback, fallback)) + b.add_resource(_PRINCIPALS[kind][0], suffix, items, when=when) + b.main_when = principals[main][3] + + +class IamManagedPolicy(ResourceConverter): + """AWS::IAM::ManagedPolicy as aws_iam_policy, with one attachment per principal.""" + + cfn_type = "AWS::IAM::ManagedPolicy" + tf_type = "aws_iam_policy" + ref = "arn" + attrs = {"PolicyArn": "arn", "PolicyId": "policy_id"} + + def convert(self, b: Builder) -> None: + """The policy and its attachments to the listed roles, users and groups.""" + p = b.props + p.attr("name", "ManagedPolicyName") + p.attr("description", "Description") + p.attr("path", "Path") + p.json("policy", "PolicyDocument") + targets = _policy_targets(b.resource) + _take_targets(b) + suffixes = UniqueNames() + for index, (kind, item) in enumerate(targets, 1): + _, tf_type, argument = _PRINCIPALS[kind] + when, target = b.ctx.optional_item(item) + label = _target_name(target) or f"{kind}_{index}" + suffix = suffixes.take("_" + identifier(label, f"{kind}_{index}")) + b.add_resource( + tf_type, + suffix, + [Attr(argument, b.ctx.expr(target)), Attr("policy_arn", b.self_ref("arn"))], + when=when, + ) + + +class IamInstanceProfile(ResourceConverter): + """AWS::IAM::InstanceProfile as aws_iam_instance_profile.""" + + cfn_type = "AWS::IAM::InstanceProfile" + tf_type = "aws_iam_instance_profile" + ref = "name" + attrs = {"Arn": "arn"} + import_id = "InstanceProfileName" + + def convert(self, b: Builder) -> None: + """The profile and its one role.""" + p = b.props + p.attr("name", "InstanceProfileName") + p.attr("path", "Path") + roles = p.peek("Roles") + if isinstance(roles, list) and len(roles) == 1: + # IAM allows one role per instance profile, as does CloudFormation. + p.drop("Roles") + p.set("role", b.ctx.expr(roles[0])) + + +class IamUser(ResourceConverter): + """AWS::IAM::User as aws_iam_user, with its groups and policies as separate + resources.""" + + cfn_type = "AWS::IAM::User" + tf_type = "aws_iam_user" + ref = "name" + attrs = {"Arn": "arn"} + import_id = "UserName" + + def convert(self, b: Builder) -> None: + """The user, its group membership, inline policies and managed policy + attachments.""" + p = b.props + b.name_attr("name", "UserName") + p.attr("path", "Path") + p.attr("permissions_boundary", "PermissionsBoundary") + p.tags() + groups = p.take("Groups") + if groups is not None: + b.add_resource( + "aws_iam_user_group_membership", + "_groups", + [Attr("user", b.self_ref("name")), Attr("groups", b.ctx.expr(groups))], + ) + _inline_policies(b, "user") + _managed_policies(b, "user") + + +class IamGroup(ResourceConverter): + """AWS::IAM::Group as aws_iam_group, with its policies as separate resources.""" + + cfn_type = "AWS::IAM::Group" + tf_type = "aws_iam_group" + ref = "name" + attrs = {"Arn": "arn"} + import_id = "GroupName" + + def convert(self, b: Builder) -> None: + """The group, its inline policies and its managed policy attachments.""" + p = b.props + b.name_attr("name", "GroupName") + p.attr("path", "Path") + _inline_policies(b, "group") + _managed_policies(b, "group") + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + IamRole, + IamPolicy, + IamManagedPolicy, + IamInstanceProfile, + IamUser, + IamGroup, +) diff --git a/services/converter-api/converters/cfn/resources/messaging.py b/services/converter-api/converters/cfn/resources/messaging.py new file mode 100644 index 0000000..c0ab3b4 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/messaging.py @@ -0,0 +1,634 @@ +"""SQS, SNS, EventBridge, Kinesis and Step Functions.""" + +from __future__ import annotations + +import json +from typing import Any, ClassVar + +from converters.cfn import hcl +from converters.cfn.builder import Builder, Props, snippet +from converters.cfn.context import Context +from converters.cfn.expressions import NO_VALUE, SUB_VARIABLE, intrinsic_name, wrap_operand +from converters.cfn.models import Attr, Call, Expression, Raw, ResourceInfo +from converters.cfn.naming import UniqueNames, identifier +from converters.cfn.resources.base import ResourceConverter + +# --- helpers shared with other modules -------------------------------------------------- + + +def operand(value: Any) -> str: + """An HCL value as an operand of `==`: in parentheses unless it is a plain reference or + string (`a ? b : c == d` would compare c alone).""" + return wrap_operand(hcl.inline(value)) + + +def optional(value: Any) -> bool: + """Whether a list item is `!If [Cond, x, !Ref AWS::NoValue]` (either way round): an item + that only exists when a condition holds. Usable before conversion (no Context).""" + if not (isinstance(value, dict) and intrinsic_name(value) == "Fn::If"): + return False + args = value["Fn::If"] + return isinstance(args, list) and len(args) == 3 and (NO_VALUE in args[1:]) + + +def main_index(values: list[Any]) -> int: + """Which of several targets gets the main resource: the first that is always there.""" + return next((i for i, value in enumerate(values) if not optional(value)), 0) + + +def sub_json(value: dict[str, Any]) -> Any: + """`!Sub '{...json...}'` (a state machine definition, a dashboard body) parsed into a + structure with Fn::Sub strings, so it becomes jsonencode({...}) instead of one long + string. None if the text is no JSON.""" + args = value["Fn::Sub"] + text, variables = ( + (args[0], args[1]) if isinstance(args, list) and len(args) == 2 else (args, {}) + ) + if not isinstance(text, str) or not isinstance(variables, dict): + return None + try: + parsed = json.loads(text) + except ValueError: + return None + return _sub_strings(parsed, variables) + + +def _sub_strings(node: Any, variables: dict[str, Any]) -> Any: + """A parsed JSON document with every string that has placeholders as a Fn::Sub.""" + if isinstance(node, dict): + return {k: _sub_strings(v, variables) for k, v in node.items()} + if isinstance(node, list): + return [_sub_strings(v, variables) for v in node] + if isinstance(node, str) and SUB_VARIABLE.search(node): + return {"Fn::Sub": [node, variables]} if variables else {"Fn::Sub": node} + return node + + +# --- helpers of this module ------------------------------------------------------------- + + +def _one_per_target( + b: Builder, cfn_name: str, tf_type: str, argument: str, items: list[Any] +) -> None: + """Resource policies that CloudFormation applies to a list of targets (queues, topics): + the first target that is always there is the main resource, each further one gets a + copy. `!If [Cond, x, !Ref AWS::NoValue]` targets get counted copies.""" + targets = b.props.peek(cfn_name) + if isinstance(targets, list): + targets = [target for target in targets if not b.ctx.is_no_value(target)] + if not isinstance(targets, list) or not targets: + # A computed list: finish() keeps it as a comment and reports it. + b.props.items.extend(items) + return + b.props.drop(cfn_name) + main = main_index(targets) + suffixes = UniqueNames() + for index, item in enumerate(targets, 1): + when, target = b.ctx.optional_item(item) + if index - 1 == main: + b.props.items.insert(0, Attr(argument, b.ctx.expr(target))) + b.props.items.extend(items) + b.main_when = when + continue + label = str(target["Ref"]) if isinstance(target, dict) and "Ref" in target else "" + suffix = suffixes.take("_" + identifier(label or f"target_{index}", f"target_{index}")) + body = [Attr(argument, b.ctx.expr(target))] + items + b.add_resource(tf_type, suffix, body, when=when) + + +def _list_item(p: Props, item: Any, where: str, tf_type: str) -> tuple[str | None, Any]: + """One entry of a list of structures that each become a resource: (condition, mapping). + `!If [Cond, {...}, !Ref AWS::NoValue]` gives a counted resource; any other function is + reported and kept as a comment, and the mapping is None.""" + when, value = p.ctx.optional_item(item) + if isinstance(value, dict) and intrinsic_name(value) is None: + return when, value + p.ctx.note( + f"{p.owner}: '{where}' is computed by a function and was not converted; add the " + f"{tf_type} by hand" + ) + p.comment(f"{where.split('.', 1)[-1]} was not converted: {snippet(item)}") + return None, None + + +def _dead_letter_config(d: Props) -> None: + """A dead_letter_config block: the queue ARN.""" + d.attr("arn", "Arn") + + +# --- SQS -------------------------------------------------------------------------------- + + +class SqsQueue(ResourceConverter): + """AWS::SQS::Queue as aws_sqs_queue.""" + + cfn_type = "AWS::SQS::Queue" + tf_type = "aws_sqs_queue" + ref = "url" + attrs = {"Arn": "arn", "QueueName": "name", "QueueUrl": "url"} + + def convert(self, b: Builder) -> None: + """The queue settings, with the JSON policies as jsonencode().""" + p = b.props + p.attr("name", "QueueName") + p.boolean("fifo_queue", "FifoQueue") + p.boolean("content_based_deduplication", "ContentBasedDeduplication") + p.attr("deduplication_scope", "DeduplicationScope") + p.attr("fifo_throughput_limit", "FifoThroughputLimit") + p.number("visibility_timeout_seconds", "VisibilityTimeout") + p.number("message_retention_seconds", "MessageRetentionPeriod") + p.number("delay_seconds", "DelaySeconds") + p.number("max_message_size", "MaximumMessageSize") + p.number("receive_wait_time_seconds", "ReceiveMessageWaitTimeSeconds") + p.attr("kms_master_key_id", "KmsMasterKeyId") + p.number("kms_data_key_reuse_period_seconds", "KmsDataKeyReusePeriodSeconds") + p.boolean("sqs_managed_sse_enabled", "SqsManagedSseEnabled") + p.json("redrive_policy", "RedrivePolicy") + p.json("redrive_allow_policy", "RedriveAllowPolicy") + p.tags() + + +class TargetPolicy(ResourceConverter): + """A resource policy that CloudFormation applies to a list of targets: one Terraform + policy per target (see _one_per_target).""" + + # The CloudFormation property listing the targets, and the Terraform argument naming one. + targets_property: ClassVar[str] = "" + target_argument: ClassVar[str] = "" + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """References to a policy whose every target is optional need `[0]`.""" + targets = (resource.get("Properties") or {}).get(self.targets_property) + if isinstance(targets, list): + targets = [target for target in targets if target != NO_VALUE] + if targets and optional(targets[main_index(targets)]): + info.conditional = True + + def convert(self, b: Builder) -> None: + """The policy document, once per target.""" + policy = b.ctx.json(b.props.take("PolicyDocument", {})) + _one_per_target( + b, + self.targets_property, + self.tf_type, + self.target_argument, + [Attr("policy", policy)], + ) + + +class SqsQueuePolicy(TargetPolicy): + """AWS::SQS::QueuePolicy as aws_sqs_queue_policy, one per queue.""" + + cfn_type = "AWS::SQS::QueuePolicy" + tf_type = "aws_sqs_queue_policy" + targets_property = "Queues" + target_argument = "queue_url" + + +# --- SNS -------------------------------------------------------------------------------- + + +class SnsTopic(ResourceConverter): + """AWS::SNS::Topic as aws_sns_topic, with its subscriptions as separate resources.""" + + cfn_type = "AWS::SNS::Topic" + tf_type = "aws_sns_topic" + ref = "arn" + attrs = {"TopicArn": "arn", "TopicName": "name"} + + def convert(self, b: Builder) -> None: + """The topic settings, then one aws_sns_topic_subscription per subscription.""" + p = b.props + p.attr("name", "TopicName") + p.attr("display_name", "DisplayName") + p.boolean("fifo_topic", "FifoTopic") + p.boolean("content_based_deduplication", "ContentBasedDeduplication") + p.attr("fifo_throughput_scope", "FifoThroughputScope") + p.attr("kms_master_key_id", "KmsMasterKeyId") + p.number("signature_version", "SignatureVersion") + p.attr("tracing_config", "TracingConfig") + p.json("archive_policy", "ArchivePolicy") + p.json("delivery_policy", "DeliveryPolicy") + p.tags() + self.subscriptions(b) + + def subscriptions(self, b: Builder) -> None: + """The Subscription list: one aws_sns_topic_subscription each.""" + p = b.props + subscriptions = p.take("Subscription") + if subscriptions is None: + return + if not isinstance(subscriptions, list): + b.ctx.note( + f"{b.logical_id}: Subscription is computed by a function and was not " + "converted; add aws_sns_topic_subscription resources by hand" + ) + p.comment(f"Subscription was not converted: {snippet(subscriptions)}") + return + count = sum(not b.ctx.is_no_value(s) for s in subscriptions) + for index, item in enumerate(subscriptions, 1): + if b.ctx.is_no_value(item): + continue + where = f"{b.logical_id}.Subscription[{index - 1}]" + when, subscription = _list_item(p, item, where, "aws_sns_topic_subscription") + if subscription is None: + continue + inner = Props(b.ctx, subscription, where, p.owner) + inner.items.append(Attr("topic_arn", b.self_ref("arn"))) + inner.attr("protocol", "Protocol") + inner.attr("endpoint", "Endpoint") + inner.finish() + suffix = "_subscription" if count == 1 else f"_subscription_{index}" + b.add_resource("aws_sns_topic_subscription", suffix, inner.items, when=when) + + +class SnsSubscription(ResourceConverter): + """AWS::SNS::Subscription as aws_sns_topic_subscription.""" + + cfn_type = "AWS::SNS::Subscription" + tf_type = "aws_sns_topic_subscription" + ref = "arn" + + def convert(self, b: Builder) -> None: + """The subscription settings, with the JSON policies as jsonencode().""" + p = b.props + p.attr("topic_arn", "TopicArn") + p.attr("protocol", "Protocol") + p.attr("endpoint", "Endpoint") + p.json("filter_policy", "FilterPolicy") + p.attr("filter_policy_scope", "FilterPolicyScope") + p.boolean("raw_message_delivery", "RawMessageDelivery") + p.json("redrive_policy", "RedrivePolicy") + p.json("delivery_policy", "DeliveryPolicy") + p.json("replay_policy", "ReplayPolicy") + p.attr("subscription_role_arn", "SubscriptionRoleArn") + p.attr("region", "Region") + + +class SnsTopicPolicy(TargetPolicy): + """AWS::SNS::TopicPolicy as aws_sns_topic_policy, one per topic.""" + + cfn_type = "AWS::SNS::TopicPolicy" + tf_type = "aws_sns_topic_policy" + targets_property = "Topics" + target_argument = "arn" + + +# --- EventBridge ------------------------------------------------------------------------ + + +class EventsRule(ResourceConverter): + """AWS::Events::Rule as aws_cloudwatch_event_rule, with its targets as separate + aws_cloudwatch_event_target resources.""" + + cfn_type = "AWS::Events::Rule" + tf_type = "aws_cloudwatch_event_rule" + ref = "name" + attrs = {"Arn": "arn"} + + def convert(self, b: Builder) -> None: + """The rule settings, then one aws_cloudwatch_event_target per target.""" + p = b.props + p.attr("name", "Name") + p.attr("description", "Description") + bus = p.peek("EventBusName") + p.attr("event_bus_name", "EventBusName") + p.json("event_pattern", "EventPattern") + p.attr("schedule_expression", "ScheduleExpression") + p.attr("state", "State") + p.attr("role_arn", "RoleArn") + p.tags() + self.targets(b, bus) + + def targets(self, b: Builder, bus: Any) -> None: + """The Targets list. A rule on a custom bus (`bus`) needs its targets on that bus.""" + p = b.props + targets = p.take("Targets") + if targets is None: + return + if not isinstance(targets, list): + b.ctx.note( + f"{b.logical_id}: Targets is computed by a function and was not converted; add " + "aws_cloudwatch_event_target resources by hand" + ) + p.comment(f"Targets was not converted: {snippet(targets)}") + return + suffixes = UniqueNames() + for index, item in enumerate(targets, 1): + if b.ctx.is_no_value(item): + continue + where = f"{b.logical_id}.Targets[{index - 1}]" + when, target = _list_item(p, item, where, "aws_cloudwatch_event_target") + if target is None: + continue + inner = Props(b.ctx, target, where, p.owner) + inner.items.append(Attr("rule", b.self_ref("name"))) + if bus is not None and not b.ctx.is_no_value(bus): + inner.items.append(Attr("event_bus_name", b.ctx.expr(bus))) + target_id = inner.peek("Id") + inner.attr("target_id", "Id") + inner.attr("arn", "Arn") + self.fill_target(inner) + inner.finish() + label = target_id if isinstance(target_id, str) else f"target_{index}" + suffix = suffixes.take("_" + identifier(label, f"target_{index}")) + b.add_resource("aws_cloudwatch_event_target", suffix, inner.items, when=when) + + def fill_target(self, t: Props) -> None: + """The settings of one target besides its ID and ARN.""" + t.attr("role_arn", "RoleArn") + t.attr("input", "Input") + t.attr("input_path", "InputPath") + t.block("input_transformer", "InputTransformer", self.fill_input_transformer) + t.block("dead_letter_config", "DeadLetterConfig", _dead_letter_config) + t.block("retry_policy", "RetryPolicy", self.fill_retry_policy) + t.block("sqs_target", "SqsParameters", self.fill_sqs_target) + t.block("kinesis_target", "KinesisParameters", self.fill_kinesis_target) + t.block("http_target", "HttpParameters", self.fill_http_target) + t.block("batch_target", "BatchParameters", self.fill_batch_target) + t.block("ecs_target", "EcsParameters", self.fill_ecs_target) + + def fill_input_transformer(self, i: Props) -> None: + """The input_transformer block.""" + i.attr("input_paths", "InputPathsMap") + i.attr("input_template", "InputTemplate") + + def fill_retry_policy(self, r: Props) -> None: + """The retry_policy block.""" + r.number("maximum_event_age_in_seconds", "MaximumEventAgeInSeconds") + r.number("maximum_retry_attempts", "MaximumRetryAttempts") + + def fill_sqs_target(self, s: Props) -> None: + """The sqs_target block.""" + s.attr("message_group_id", "MessageGroupId") + + def fill_kinesis_target(self, k: Props) -> None: + """The kinesis_target block.""" + k.attr("partition_key_path", "PartitionKeyPath") + + def fill_http_target(self, h: Props) -> None: + """The http_target block.""" + h.attrs( + { + "header_parameters": "HeaderParameters", + "path_parameter_values": "PathParameterValues", + "query_string_parameters": "QueryStringParameters", + } + ) + + def fill_batch_target(self, r: Props) -> None: + """The batch_target block: the array size and attempts are flat in Terraform.""" + r.attr("job_definition", "JobDefinition") + r.attr("job_name", "JobName") + size = r.literal("ArrayProperties", dict) + if size is not None and "Size" in size: + r.set("array_size", r.ctx.expr(size["Size"])) + retry = r.literal("RetryStrategy", dict) + if retry is not None and "Attempts" in retry: + r.set("job_attempts", r.ctx.expr(retry["Attempts"])) + + def fill_ecs_target(self, r: Props) -> None: + """The ecs_target block.""" + r.attr("task_definition_arn", "TaskDefinitionArn") + r.number("task_count", "TaskCount") + r.attr("launch_type", "LaunchType") + r.attr("platform_version", "PlatformVersion") + r.attr("group", "Group") + r.boolean("enable_ecs_managed_tags", "EnableECSManagedTags") + r.boolean("enable_execute_command", "EnableExecuteCommand") + r.attr("propagate_tags", "PropagateTags") + r.block("network_configuration", "NetworkConfiguration", self.fill_ecs_network) + + def fill_ecs_network(self, n: Props) -> None: + """NetworkConfiguration.AwsVpcConfiguration: flat in the network_configuration of + Terraform.""" + vpc = n.literal("AwsVpcConfiguration", dict) + if vpc is None: + return + v = Props(n.ctx, vpc, f"{n.where}.AwsVpcConfiguration", n.owner) + v.list_attr("subnets", "Subnets") + v.list_attr("security_groups", "SecurityGroups") + public = v.take("AssignPublicIp") + if isinstance(public, str): + v.set("assign_public_ip", public.upper() == "ENABLED") + elif public is not None: + v.set("assign_public_ip", Raw(f'{operand(n.ctx.expr(public))} == "ENABLED"')) + v.finish() + n.items.extend(v.items) + + +class EventsEventBus(ResourceConverter): + """AWS::Events::EventBus as aws_cloudwatch_event_bus, with its policy as a separate + aws_cloudwatch_event_bus_policy.""" + + cfn_type = "AWS::Events::EventBus" + tf_type = "aws_cloudwatch_event_bus" + ref = "name" + attrs = {"Arn": "arn", "Name": "name"} + import_id = "Name" + + def convert(self, b: Builder) -> None: + """The bus settings and its policy.""" + p = b.props + b.name_attr("name", "Name") + p.attr("description", "Description") + p.attr("event_source_name", "EventSourceName") + p.attr("kms_key_identifier", "KmsKeyIdentifier") + p.block("dead_letter_config", "DeadLetterConfig", _dead_letter_config) + p.block("log_config", "LogConfig", self.fill_log_config) + p.tags() + policy = p.take("Policy") + if policy is not None: + b.add_resource( + "aws_cloudwatch_event_bus_policy", + "_policy", + [Attr("event_bus_name", b.self_ref("name")), Attr("policy", b.ctx.json(policy))], + ) + + def fill_log_config(self, c: Props) -> None: + """The log_config block.""" + c.attrs({"include_detail": "IncludeDetail", "level": "Level"}) + + +# --- Kinesis ---------------------------------------------------------------------------- + + +class KinesisStream(ResourceConverter): + """AWS::Kinesis::Stream as aws_kinesis_stream.""" + + cfn_type = "AWS::Kinesis::Stream" + tf_type = "aws_kinesis_stream" + ref = "name" + attrs = {"Arn": "arn"} + import_id = "Name" + + def convert(self, b: Builder) -> None: + """The stream settings; StreamEncryption is flat in Terraform.""" + p = b.props + b.name_attr("name", "Name") + p.number("shard_count", "ShardCount") + p.number("retention_period", "RetentionPeriodHours") + p.list_attr("shard_level_metrics", "DesiredShardLevelMetrics") + p.number("max_record_size_in_kib", "MaxRecordSizeInKiB") + encryption = p.take("StreamEncryption") + if isinstance(encryption, dict): + inner = Props(b.ctx, encryption, f"{b.logical_id}.StreamEncryption", p.owner) + inner.attr("encryption_type", "EncryptionType") + inner.attr("kms_key_id", "KeyId") + inner.finish() + p.items.extend(inner.items) + p.block("stream_mode_details", "StreamModeDetails", self.fill_stream_mode) + p.tags() + + def fill_stream_mode(self, m: Props) -> None: + """The stream_mode_details block.""" + m.attr("stream_mode", "StreamMode") + + +# --- Step Functions --------------------------------------------------------------------- + + +def _as_text(value: Any, ctx: Context) -> Any: + """A substitution value as CloudFormation pastes it into the definition: as text.""" + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, int | float): + return str(value) + if ctx.is_number_parameter(value): + return Expression(f"tostring({ctx.text(value)})") + return value + + +def _escape_unknown(text: str, known: dict[str, Any]) -> str: + """`text` with every placeholder that is no substitution escaped (`${!Name}`), so it + stays literal text.""" + pieces: list[str] = [] + last = 0 + for match in SUB_VARIABLE.finditer(text): + pieces.append(text[last : match.start()]) + name = match.group(1) + pieces.append(match.group(0) if name.strip() in known else "${!" + name + "}") + last = match.end() + pieces.append(text[last:]) + return "".join(pieces) + + +def _substitute(value: Any, substitutions: dict[str, Any], ctx: Context) -> Any: + """Strings of a state machine definition with `${Name}` placeholders as Fn::Sub, so the + substitution values (often references) become Terraform expressions. CloudFormation + replaces text, so a string stays a string whatever the type of the value.""" + if isinstance(value, dict): + return {k: _substitute(v, substitutions, ctx) for k, v in value.items()} + if isinstance(value, list): + return [_substitute(v, substitutions, ctx) for v in value] + if isinstance(value, str) and SUB_VARIABLE.search(value): + names = {m.strip() for m in SUB_VARIABLE.findall(value)} + known = { + name: _as_text(substitutions[name], ctx) for name in names if name in substitutions + } + return {"Fn::Sub": [_escape_unknown(value, known), known]} if known else value + return value + + +class StepFunctionsStateMachine(ResourceConverter): + """AWS::StepFunctions::StateMachine as aws_sfn_state_machine.""" + + cfn_type = "AWS::StepFunctions::StateMachine" + tf_type = "aws_sfn_state_machine" + ref = "arn" + attrs = {"Arn": "arn", "Name": "name"} + + def convert(self, b: Builder) -> None: + """The state machine settings and its definition.""" + p = b.props + p.attr("name", "StateMachineName") + p.attr("type", "StateMachineType") + p.attr("role_arn", "RoleArn") + self.definition(b) + p.block("logging_configuration", "LoggingConfiguration", self.fill_logging) + p.block("tracing_configuration", "TracingConfiguration", self.fill_tracing) + p.block("encryption_configuration", "EncryptionConfiguration", self.fill_encryption) + p.tags() + + def definition(self, b: Builder) -> None: + """Definition, DefinitionString and DefinitionSubstitutions as one definition: a + jsonencode() of the structure where it can be read, the text otherwise.""" + p = b.props + substitutions = p.take("DefinitionSubstitutions") + definition = p.take("Definition") + text = p.take("DefinitionString") + if definition is None and isinstance(text, str): + try: + definition = json.loads(text) + except ValueError: + definition = None + p.set("definition", text) + elif definition is None and isinstance(text, dict) and intrinsic_name(text) == "Fn::Sub": + definition = sub_json(text) + if definition is None: + p.set("definition", b.ctx.expr(text)) + elif definition is None and text is not None: + p.set("definition", b.ctx.expr(text)) + if definition is not None: + if isinstance(substitutions, dict): + definition = _substitute(definition, substitutions, b.ctx) + substitutions = None + p.set("definition", Call("jsonencode", b.ctx.expr(definition))) + if substitutions is not None: + b.ctx.note( + f"{b.logical_id}: DefinitionSubstitutions could not be applied to this " + "definition; replace the ${...} placeholders by hand" + ) + p.comment(f"DefinitionSubstitutions was not converted: {snippet(substitutions)}") + + def fill_logging(self, log: Props) -> None: + """The logging_configuration block.""" + self.log_destination(log) + log.boolean("include_execution_data", "IncludeExecutionData") + log.attr("level", "Level") + + def log_destination(self, log: Props) -> None: + """The first log group of Destinations as log_destination.""" + destinations = log.take("Destinations") + if not isinstance(destinations, list) or not destinations: + return + group = ( + destinations[0].get("CloudWatchLogsLogGroup", {}) + if isinstance(destinations[0], dict) + else {} + ) + arn = group.get("LogGroupArn") if isinstance(group, dict) else None + if arn is None: + return + value = log.ctx.expr(arn) + text = hcl.inline(value) + # Step Functions wants the log group ARN with its ':*' suffix. + if not text.endswith(':*"'): + if isinstance(value, str): + value = value + ":*" + else: + value = Raw('"${' + text + '}:*"') + log.set("log_destination", value) + + def fill_tracing(self, t: Props) -> None: + """The tracing_configuration block.""" + t.boolean("enabled", "Enabled") + + def fill_encryption(self, e: Props) -> None: + """The encryption_configuration block.""" + e.attr("kms_key_id", "KmsKeyId") + e.number("kms_data_key_reuse_period_seconds", "KmsDataKeyReusePeriodSeconds") + e.attr("type", "Type") + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + SqsQueue, + SqsQueuePolicy, + SnsTopic, + SnsSubscription, + SnsTopicPolicy, + EventsRule, + EventsEventBus, + KinesisStream, + StepFunctionsStateMachine, +) diff --git a/services/converter-api/converters/cfn/resources/network.py b/services/converter-api/converters/cfn/resources/network.py new file mode 100644 index 0000000..2a1ad10 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/network.py @@ -0,0 +1,1772 @@ +"""VPC networking, load balancers, Route 53, ACM and CloudFront.""" + +from __future__ import annotations + +from collections.abc import Callable +from operator import attrgetter +from typing import Any, ClassVar + +from converters.cfn import hcl +from converters.cfn.builder import Builder, Props, snippet +from converters.cfn.context import Context +from converters.cfn.expressions import intrinsic_name, wrap_operand +from converters.cfn.models import BLANK, Attr, Block, Comment, Raw, ResourceInfo +from converters.cfn.resources.base import ResourceConverter + +# --- helpers ---------------------------------------------------------------------------- + +NO_VALUE = {"Ref": "AWS::NoValue"} + + +def _typed(p: Props, value: Any, kind: str) -> Any: + """A value converted as a "bool", a "number" or (any other kind) an expression.""" + if kind == "bool": + return p.as_bool(value) + if kind == "number": + return p.as_number(value) + return p.ctx.expr(value) + + +def _as_list(ctx: Context, value: Any) -> Any: + """A single CloudFormation value where Terraform wants a list.""" + converted = ctx.expr(value) + if isinstance(value, list) or isinstance(converted, list): + return converted + if isinstance(value, dict) and intrinsic_name(value) in ("Fn::GetAZs", "Fn::Split"): + return converted + return [converted] + + +def _list_attr(p: Props, tf_name: str, cfn_name: str) -> None: + """A property as a list attribute, with a single value put in a list (see _as_list).""" + value = p.take(cfn_name) + if value is not None: + p.set(tf_name, _as_list(p.ctx, value)) + + +class OptionalList: + """The condition of `!If [Cond, [items], !Ref AWS::NoValue]` (either way round), so each + item can carry it on its own.""" + + def __init__(self, condition: Any, when_true: bool) -> None: + """`condition` is the condition name; `when_true` says whether the items exist when + it holds (the NoValue branch is the second one).""" + self.condition = condition + self.when_true = when_true + + def present(self, item: Any) -> dict[str, Any]: + """`item` as it holds only when the list is present.""" + if self.when_true: + return {"Fn::If": [self.condition, item, NO_VALUE]} + return {"Fn::If": [self.condition, NO_VALUE, item]} + + def absent(self, item: Any) -> dict[str, Any]: + """`item` as it holds only when the list is absent.""" + if self.when_true: + return {"Fn::If": [self.condition, NO_VALUE, item]} + return {"Fn::If": [self.condition, item, NO_VALUE]} + + +def _split_if(ctx: Context, items: Any) -> tuple[Any, OptionalList | None]: + """`!If [Cond, [items], !Ref AWS::NoValue]` (either way round) as one `!If` per item, so + each becomes a conditional block or resource. Also returns the condition, to wrap an item + that holds only when the property is absent. Anything else is returned as it is (and + None).""" + if not (isinstance(items, dict) and intrinsic_name(items) == "Fn::If"): + return items, None + args = items["Fn::If"] + if not isinstance(args, list) or len(args) != 3: + return items, None + name, yes, no = args + if ctx.is_no_value(no) and not ctx.is_no_value(yes): + optional = OptionalList(name, when_true=True) + present = yes if isinstance(yes, list) else [yes] + elif ctx.is_no_value(yes) and not ctx.is_no_value(no): + optional = OptionalList(name, when_true=False) + present = no if isinstance(no, list) else [no] + else: + return items, None + return [optional.present(item) for item in present], optional + + +def _blocks(p: Props, tf_name: str, cfn_name: str, fill: Callable[[Props], None]) -> None: + """A list of structures as blocks, like Props.block, where `!If [Cond, [...], + !Ref AWS::NoValue]` around the whole list gives one conditional block per item.""" + value = p.take(cfn_name) + if value is None: + return + items, _ = _split_if(p.ctx, value) + p.add_blocks(tf_name, items, fill, f"{p.where}.{cfn_name}") + + +def _sub(p: Props, value: Any, name: str) -> Props: + """The properties of the structure `name` inside `p`.""" + return Props(p.ctx, value, f"{p.where}.{name}", p.owner) + + +def _refers_to(value: Any, logical_id: str) -> bool: + """Whether a value is `!Ref logical_id` or `!GetAtt logical_id.`.""" + if not isinstance(value, dict): + return False + if value.get("Ref") == logical_id: + return True + get_att = value.get("Fn::GetAtt") + if isinstance(get_att, str): + return get_att.split(".", 1)[0] == logical_id + return isinstance(get_att, list) and bool(get_att) and get_att[0] == logical_id + + +def _ipv6_blocks(info: ResourceInfo) -> None: + """CloudFormation returns a list of IPv6 blocks; the provider holds the one block as a + string.""" + info.attrs["Ipv6CidrBlocks"] = "ipv6_cidr_blocks" + info.overrides["ipv6_cidr_blocks"] = f"[{info.expression('ipv6_cidr_block')}]" + + +def _nested(b: Builder, name: str, fill: Callable[[Props], None]) -> None: + """A resource whose properties all sit in one configuration structure.""" + inner = Props(b.ctx, b.props.take(name), f"{b.logical_id}.{name}", b.props.owner) + fill(inner) + inner.finish() + b.props.items.extend(inner.items) + + +# --- VPC basics ------------------------------------------------------------------------- + + +class Vpc(ResourceConverter): + """AWS::EC2::VPC as aws_vpc.""" + + cfn_type = "AWS::EC2::VPC" + tf_type = "aws_vpc" + attrs: ClassVar[dict[str, str]] = { + "CidrBlock": "cidr_block", + "DefaultNetworkAcl": "default_network_acl_id", + "DefaultSecurityGroup": "default_security_group_id", + "VpcId": "id", + } + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """Ipv6CidrBlocks reads the one IPv6 block as a list.""" + _ipv6_blocks(info) + + def convert(self, b: Builder) -> None: + """The CIDR block, DNS settings and tags.""" + p = b.props + p.attr("cidr_block", "CidrBlock") + p.attr("ipv4_ipam_pool_id", "Ipv4IpamPoolId") + p.number("ipv4_netmask_length", "Ipv4NetmaskLength") + p.boolean("enable_dns_support", "EnableDnsSupport") + p.boolean("enable_dns_hostnames", "EnableDnsHostnames") + p.attr("instance_tenancy", "InstanceTenancy") + p.tags() + + +class Subnet(ResourceConverter): + """AWS::EC2::Subnet as aws_subnet.""" + + cfn_type = "AWS::EC2::Subnet" + tf_type = "aws_subnet" + attrs: ClassVar[dict[str, str]] = { + "AvailabilityZone": "availability_zone", + "AvailabilityZoneId": "availability_zone_id", + "CidrBlock": "cidr_block", + "OutpostArn": "outpost_arn", + "SubnetId": "id", + "VpcId": "vpc_id", + } + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """Ipv6CidrBlocks reads the one IPv6 block as a list.""" + _ipv6_blocks(info) + + def convert(self, b: Builder) -> None: + """The addresses, the zone and the launch options, which are flat attributes in + Terraform.""" + p = b.props + p.attr("vpc_id", "VpcId") + p.attr("cidr_block", "CidrBlock") + p.attr("availability_zone", "AvailabilityZone") + p.attr("availability_zone_id", "AvailabilityZoneId") + p.boolean("map_public_ip_on_launch", "MapPublicIpOnLaunch") + p.attr("ipv6_cidr_block", "Ipv6CidrBlock") + p.boolean("assign_ipv6_address_on_creation", "AssignIpv6AddressOnCreation") + p.boolean("ipv6_native", "Ipv6Native") + p.boolean("enable_dns64", "EnableDns64") + p.attr("ipv4_ipam_pool_id", "Ipv4IpamPoolId") + p.number("ipv4_netmask_length", "Ipv4NetmaskLength") + p.attr("ipv6_ipam_pool_id", "Ipv6IpamPoolId") + p.number("ipv6_netmask_length", "Ipv6NetmaskLength") + p.attr("outpost_arn", "OutpostArn") + options = p.take("PrivateDnsNameOptionsOnLaunch") + if options is not None: + inner = _sub(p, options, "PrivateDnsNameOptionsOnLaunch") + inner.attr("private_dns_hostname_type_on_launch", "HostnameType") + inner.boolean( + "enable_resource_name_dns_a_record_on_launch", "EnableResourceNameDnsARecord" + ) + inner.boolean( + "enable_resource_name_dns_aaaa_record_on_launch", "EnableResourceNameDnsAAAARecord" + ) + inner.finish() + p.items.extend(inner.items) + p.tags() + + +class InternetGateway(ResourceConverter): + """AWS::EC2::InternetGateway as aws_internet_gateway.""" + + cfn_type = "AWS::EC2::InternetGateway" + tf_type = "aws_internet_gateway" + attrs: ClassVar[dict[str, str]] = {"InternetGatewayId": "id"} + + def convert(self, b: Builder) -> None: + """Only tags.""" + b.props.tags() + + +class EgressOnlyInternetGateway(ResourceConverter): + """AWS::EC2::EgressOnlyInternetGateway as aws_egress_only_internet_gateway.""" + + cfn_type = "AWS::EC2::EgressOnlyInternetGateway" + tf_type = "aws_egress_only_internet_gateway" + + def convert(self, b: Builder) -> None: + """The VPC and tags.""" + b.props.attr("vpc_id", "VpcId") + b.props.tags() + + +class VpcGatewayAttachment(ResourceConverter): + """AWS::EC2::VPCGatewayAttachment as aws_internet_gateway_attachment, or as + aws_vpn_gateway_attachment for a VPN gateway.""" + + cfn_type = "AWS::EC2::VPCGatewayAttachment" + tf_type = "aws_internet_gateway_attachment" + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """A VPN gateway attachment has a Terraform type of its own.""" + properties = resource.get("Properties") or {} + if ( + properties.get("VpnGatewayId") is not None + and properties.get("InternetGatewayId") is None + ): + info.tf_type = "aws_vpn_gateway_attachment" + + def convert(self, b: Builder) -> None: + """The VPC and the gateway.""" + p = b.props + if b.info.tf_type == "aws_vpn_gateway_attachment": + p.attr("vpc_id", "VpcId") + p.attr("vpn_gateway_id", "VpnGatewayId") + return + p.attr("internet_gateway_id", "InternetGatewayId") + p.attr("vpc_id", "VpcId") + + +class RouteTable(ResourceConverter): + """AWS::EC2::RouteTable as aws_route_table.""" + + cfn_type = "AWS::EC2::RouteTable" + tf_type = "aws_route_table" + attrs: ClassVar[dict[str, str]] = {"RouteTableId": "id"} + + def convert(self, b: Builder) -> None: + """The VPC and tags.""" + b.props.attr("vpc_id", "VpcId") + b.props.tags() + + +class Route(ResourceConverter): + """AWS::EC2::Route as aws_route.""" + + cfn_type = "AWS::EC2::Route" + tf_type = "aws_route" + + def convert(self, b: Builder) -> None: + """The destination and the target. An instance target is reported.""" + b.props.attrs( + { + "route_table_id": "RouteTableId", + "destination_cidr_block": "DestinationCidrBlock", + "destination_ipv6_cidr_block": "DestinationIpv6CidrBlock", + "destination_prefix_list_id": "DestinationPrefixListId", + "gateway_id": "GatewayId", + "nat_gateway_id": "NatGatewayId", + "network_interface_id": "NetworkInterfaceId", + "transit_gateway_id": "TransitGatewayId", + "vpc_peering_connection_id": "VpcPeeringConnectionId", + "vpc_endpoint_id": "VpcEndpointId", + "egress_only_gateway_id": "EgressOnlyInternetGatewayId", + "carrier_gateway_id": "CarrierGatewayId", + "local_gateway_id": "LocalGatewayId", + "core_network_arn": "CoreNetworkArn", + } + ) + if b.props.has("InstanceId"): + b.ctx.note( + f"{b.logical_id} routes to an instance: the aws provider routes to its network " + "interface instead (network_interface_id = aws_instance.." + "primary_network_interface_id)" + ) + + +class SubnetRouteTableAssociation(ResourceConverter): + """AWS::EC2::SubnetRouteTableAssociation as aws_route_table_association.""" + + cfn_type = "AWS::EC2::SubnetRouteTableAssociation" + tf_type = "aws_route_table_association" + + def convert(self, b: Builder) -> None: + """The subnet and the route table.""" + b.props.attr("subnet_id", "SubnetId") + b.props.attr("route_table_id", "RouteTableId") + + +class Eip(ResourceConverter): + """AWS::EC2::EIP as aws_eip.""" + + cfn_type = "AWS::EC2::EIP" + tf_type = "aws_eip" + ref = "public_ip" + attrs: ClassVar[dict[str, str]] = {"AllocationId": "allocation_id", "PublicIp": "public_ip"} + + def convert(self, b: Builder) -> None: + """The address settings and tags.""" + p = b.props + p.attr("domain", "Domain") + p.attr("instance", "InstanceId") + p.attr("network_border_group", "NetworkBorderGroup") + p.attr("public_ipv4_pool", "PublicIpv4Pool") + p.attr("ipam_pool_id", "IpamPoolId") + p.attr("address", "Address") + p.tags() + + +class EipAssociation(ResourceConverter): + """AWS::EC2::EIPAssociation as aws_eip_association.""" + + cfn_type = "AWS::EC2::EIPAssociation" + tf_type = "aws_eip_association" + + def convert(self, b: Builder) -> None: + """The address and what it is associated with.""" + b.props.attrs( + { + "allocation_id": "AllocationId", + "public_ip": "EIP", + "instance_id": "InstanceId", + "network_interface_id": "NetworkInterfaceId", + "private_ip_address": "PrivateIpAddress", + } + ) + + +class NatGateway(ResourceConverter): + """AWS::EC2::NatGateway as aws_nat_gateway.""" + + cfn_type = "AWS::EC2::NatGateway" + tf_type = "aws_nat_gateway" + attrs: ClassVar[dict[str, str]] = {"NatGatewayId": "id"} + + def convert(self, b: Builder) -> None: + """The subnet, the addresses and tags.""" + p = b.props + p.attr("allocation_id", "AllocationId") + p.attr("subnet_id", "SubnetId") + p.attr("connectivity_type", "ConnectivityType") + p.attr("private_ip", "PrivateIpAddress") + p.attr("secondary_allocation_ids", "SecondaryAllocationIds") + p.attr("secondary_private_ip_addresses", "SecondaryPrivateIpAddresses") + p.number("secondary_private_ip_address_count", "SecondaryPrivateIpAddressCount") + p.tags() + + +class VpcEndpoint(ResourceConverter): + """AWS::EC2::VPCEndpoint as aws_vpc_endpoint.""" + + cfn_type = "AWS::EC2::VPCEndpoint" + tf_type = "aws_vpc_endpoint" + attrs: ClassVar[dict[str, str]] = {"Id": "id", "NetworkInterfaceIds": "network_interface_ids"} + + def convert(self, b: Builder) -> None: + """The service, the network placement, the policy and DNS options.""" + p = b.props + p.attr("vpc_id", "VpcId") + p.attr("service_name", "ServiceName") + p.attr("vpc_endpoint_type", "VpcEndpointType") + p.boolean("private_dns_enabled", "PrivateDnsEnabled") + p.attr("ip_address_type", "IpAddressType") + p.list_attr("route_table_ids", "RouteTableIds") + p.list_attr("subnet_ids", "SubnetIds") + p.list_attr("security_group_ids", "SecurityGroupIds") + p.json("policy", "PolicyDocument") + p.block("dns_options", "DnsOptions", self.fill_dns_options) + p.tags() + + def fill_dns_options(self, d: Props) -> None: + """The dns_options block.""" + d.attr("dns_record_ip_type", "DnsRecordIpType") + d.boolean( + "private_dns_only_for_inbound_resolver_endpoint", + "PrivateDnsOnlyForInboundResolverEndpoint", + ) + + +# --- security groups -------------------------------------------------------------------- + +ALL_PROTOCOLS = ("-1", "all") +ICMP_PROTOCOLS = ("icmp", "icmpv6", "1", "58") +ALLOW_ALL_EGRESS = {"IpProtocol": "-1", "CidrIp": "0.0.0.0/0"} +EGRESS_COMMENT = ( + "CloudFormation adds this allow-all egress rule when the template has none;\n" + "Terraform removes it, so it is written out." +) + + +def _protocol(value: Any) -> str | None: + """The protocol as lowercase text when it is a literal, else None.""" + if isinstance(value, str | int) and not isinstance(value, bool): + return str(value).lower() + return None + + +def _rule_target(egress: bool) -> tuple[str, str]: + """CloudFormation names of the other side of a rule: (security group, prefix list).""" + if egress: + return "DestinationSecurityGroupId", "DestinationPrefixListId" + return "SourceSecurityGroupId", "SourcePrefixListId" + + +def _inline_rule(r: Props, egress: bool) -> None: + """One SecurityGroupIngress/SecurityGroupEgress entry as an inline ingress/egress block.""" + protocol = r.take("IpProtocol", "-1") + literal = _protocol(protocol) + from_port, to_port = r.take("FromPort"), r.take("ToPort") + if literal in ALL_PROTOCOLS: + r.set("from_port", 0) + r.set("to_port", 0) + r.set("protocol", "-1") + else: + # Leaving the ports out means all of them (or every ICMP type and code). + icmp = literal in ICMP_PROTOCOLS + first = (-1 if icmp else 0) if from_port is None else r.as_number(from_port) + if to_port is not None: + last = r.as_number(to_port) + elif from_port is not None: + last = first + else: + last = -1 if icmp else 65535 + r.set("from_port", first) + r.set("to_port", last) + r.set("protocol", literal if literal is not None else r.ctx.expr(protocol)) + group, prefix = _rule_target(egress) + _list_attr(r, "cidr_blocks", "CidrIp") + _list_attr(r, "ipv6_cidr_blocks", "CidrIpv6") + _list_attr(r, "security_groups", group) + _list_attr(r, "prefix_list_ids", prefix) + r.attr("description", "Description") + + +def _inline_ingress(r: Props) -> None: + """An inline ingress block.""" + _inline_rule(r, egress=False) + + +def _inline_egress(r: Props) -> None: + """An inline egress block.""" + _inline_rule(r, egress=True) + + +def _rule_items(r: Props, egress: bool) -> None: + """One rule as an aws_vpc_security_group_ingress_rule / egress_rule body.""" + protocol = r.take("IpProtocol", "-1") + literal = _protocol(protocol) + from_port, to_port = r.take("FromPort"), r.take("ToPort") + if literal in ALL_PROTOCOLS: + # With every protocol the API takes no ports. + r.set("ip_protocol", "-1") + else: + r.set("ip_protocol", literal if literal is not None else r.ctx.expr(protocol)) + if from_port is not None: + r.set("from_port", r.as_number(from_port)) + if to_port is not None: + r.set("to_port", r.as_number(to_port)) + group, prefix = _rule_target(egress) + r.attr("cidr_ipv4", "CidrIp") + r.attr("cidr_ipv6", "CidrIpv6") + r.attr("referenced_security_group_id", group) + r.attr("prefix_list_id", prefix) + r.attr("description", "Description") + + +class SecurityGroup(ResourceConverter): + """AWS::EC2::SecurityGroup as aws_security_group, with its rules inline, or as rule + resources when other rule resources point at the group.""" + + cfn_type = "AWS::EC2::SecurityGroup" + tf_type = "aws_security_group" + attrs: ClassVar[dict[str, str]] = {"GroupId": "id", "VpcId": "vpc_id"} + + def convert(self, b: Builder) -> None: + """The group and its rules, with the default egress rule CloudFormation adds.""" + p = b.props + p.attr("name", "GroupName") + p.attr("description", "GroupDescription") + p.attr("vpc_id", "VpcId") + p.tags() + ingress, _ = _split_if(b.ctx, p.take("SecurityGroupIngress")) + egress, optional = _split_if(b.ctx, p.take("SecurityGroupEgress")) + # The rule CloudFormation keeps when the template sets no egress (or, for + # `!If [Cond, [...], !Ref AWS::NoValue]`, when the condition picks NoValue). + default: Any = None + if egress is None: + default = ALLOW_ALL_EGRESS + egress = [default] + elif optional is not None: + default = optional.absent(ALLOW_ALL_EGRESS) + egress = egress + [default] + + if self.has_standalone_rules(b.ctx, b.logical_id): + # Inline rules and separate rule resources on one group overwrite each other in + # Terraform, so this group's own rules become separate resources too. + self.standalone_rules(b, "ingress", ingress, None) + self.standalone_rules(b, "egress", egress, default) + return + if ingress is not None: + p.add_blocks("ingress", ingress, _inline_ingress, f"{p.where}.Ingress") + for rule in egress if isinstance(egress, list) else [egress]: + if rule is default: + p.comment(EGRESS_COMMENT) + p.add_blocks("egress", rule, _inline_egress, f"{p.where}.Egress") + + def has_standalone_rules(self, ctx: Context, logical_id: str) -> bool: + """Whether a rule resource of the template points at this group.""" + for other in (ctx.template.get("Resources") or {}).values(): + if other.get("Type") in ( + "AWS::EC2::SecurityGroupIngress", + "AWS::EC2::SecurityGroupEgress", + ): + if _refers_to((other.get("Properties") or {}).get("GroupId"), logical_id): + return True + return False + + def standalone_rules(self, b: Builder, kind: str, rules: Any, default: Any) -> None: + """The group's own `kind` ("ingress" or "egress") rules as rule resources.""" + if rules is None: + return + if not isinstance(rules, list): + b.ctx.note( + f"{b.logical_id}: the {kind} rules are computed by a function, so they were not " + "turned into rule resources; add them by hand" + ) + return + is_egress = kind == "egress" + for number, item in enumerate(rules, start=1): + if b.ctx.is_no_value(item): + continue + where = f"{b.logical_id}.{kind}[{number - 1}]" + # `!If [Cond, {...}, !Ref AWS::NoValue]`: a rule resource counted on Cond. + when, rule = b.ctx.optional_item(item) + if not isinstance(rule, dict) or intrinsic_name(rule) is not None: + b.ctx.note( + f"{b.props.owner}: '{where}' is computed by a function and was not " + f"converted; add the aws_vpc_security_group_{kind}_rule by hand" + ) + b.props.comment(f"{kind}[{number - 1}] was not converted: {snippet(item)}") + continue + inner = Props(b.ctx, rule, where, b.props.owner) + items: list[Any] = [Attr("security_group_id", b.self_ref("id"))] + if is_egress and item is default: + items.insert(0, Comment(EGRESS_COMMENT)) + _rule_items(inner, is_egress) + inner.finish() + b.add_resource( + f"aws_vpc_security_group_{kind}_rule", + f"_{kind}_{number}", + items + inner.items, + when=when, + ) + + +class SecurityGroupIngress(ResourceConverter): + """AWS::EC2::SecurityGroupIngress as aws_vpc_security_group_ingress_rule.""" + + cfn_type = "AWS::EC2::SecurityGroupIngress" + tf_type = "aws_vpc_security_group_ingress_rule" + egress: ClassVar[bool] = False + + def convert(self, b: Builder) -> None: + """The group and the rule.""" + b.props.attr("security_group_id", "GroupId") + _rule_items(b.props, self.egress) + + +class SecurityGroupEgress(SecurityGroupIngress): + """AWS::EC2::SecurityGroupEgress as aws_vpc_security_group_egress_rule.""" + + cfn_type = "AWS::EC2::SecurityGroupEgress" + tf_type = "aws_vpc_security_group_egress_rule" + egress: ClassVar[bool] = True + + +# --- network ACLs and flow logs --------------------------------------------------------- + + +class NetworkAcl(ResourceConverter): + """AWS::EC2::NetworkAcl as aws_network_acl.""" + + cfn_type = "AWS::EC2::NetworkAcl" + tf_type = "aws_network_acl" + + def convert(self, b: Builder) -> None: + """The VPC and tags.""" + b.props.attr("vpc_id", "VpcId") + b.props.tags() + + +class NetworkAclEntry(ResourceConverter): + """AWS::EC2::NetworkAclEntry as aws_network_acl_rule.""" + + cfn_type = "AWS::EC2::NetworkAclEntry" + tf_type = "aws_network_acl_rule" + + def convert(self, b: Builder) -> None: + """The rule, with the port range and ICMP settings as flat attributes.""" + p, ctx = b.props, b.ctx + p.attr("network_acl_id", "NetworkAclId") + p.number("rule_number", "RuleNumber") + p.boolean("egress", "Egress") + protocol = p.take("Protocol") + if protocol is not None: + literal = _protocol(protocol) + p.set("protocol", literal if literal is not None else ctx.expr(protocol)) + p.attr("rule_action", "RuleAction") + p.attr("cidr_block", "CidrBlock") + p.attr("ipv6_cidr_block", "Ipv6CidrBlock") + ports = p.take("PortRange") + if isinstance(ports, dict): + for key, tf_name in (("From", "from_port"), ("To", "to_port")): + if ports.get(key) is not None: + p.set(tf_name, p.as_number(ports[key])) + icmp = p.take("Icmp") + if isinstance(icmp, dict): + for key, tf_name in (("Type", "icmp_type"), ("Code", "icmp_code")): + if icmp.get(key) is not None: + p.set(tf_name, p.as_number(icmp[key])) + + +class SubnetNetworkAclAssociation(ResourceConverter): + """AWS::EC2::SubnetNetworkAclAssociation as aws_network_acl_association.""" + + cfn_type = "AWS::EC2::SubnetNetworkAclAssociation" + tf_type = "aws_network_acl_association" + + def convert(self, b: Builder) -> None: + """The network ACL and the subnet.""" + b.props.attr("network_acl_id", "NetworkAclId") + b.props.attr("subnet_id", "SubnetId") + + +class FlowLog(ResourceConverter): + """AWS::EC2::FlowLog as aws_flow_log.""" + + cfn_type = "AWS::EC2::FlowLog" + tf_type = "aws_flow_log" + # ResourceType -> the attribute that takes ResourceId. + targets: ClassVar[dict[str, str]] = { + "VPC": "vpc_id", + "Subnet": "subnet_id", + "NetworkInterface": "eni_id", + "TransitGateway": "transit_gateway_id", + "TransitGatewayAttachment": "transit_gateway_attachment_id", + "RegionalNatGateway": "regional_nat_gateway_id", + } + log_group_arn = "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:${Name}" + + def convert(self, b: Builder) -> None: + """What is logged, where to and in what format.""" + p, ctx = b.props, b.ctx + kind = p.peek("ResourceType") + if isinstance(kind, str) and kind in self.targets and p.has("ResourceId"): + p.drop("ResourceType") + p.attr(self.targets[kind], "ResourceId") + p.attr("traffic_type", "TrafficType") + p.attr("log_destination_type", "LogDestinationType") + p.attr("log_destination", "LogDestination") + group = p.take("LogGroupName") + if group is not None: + # The provider only takes the ARN of the log group. + p.set("log_destination", ctx.expr({"Fn::Sub": [self.log_group_arn, {"Name": group}]})) + p.attr("iam_role_arn", "DeliverLogsPermissionArn") + p.attr("deliver_cross_account_role", "DeliverCrossAccountRole") + p.attr("log_format", "LogFormat") + p.number("max_aggregation_interval", "MaxAggregationInterval") + p.block("destination_options", "DestinationOptions", self.fill_destination_options) + p.tags() + + def fill_destination_options(self, d: Props) -> None: + """The destination_options block.""" + d.attr("file_format", "FileFormat") + d.boolean("hive_compatible_partitions", "HiveCompatiblePartitions") + d.boolean("per_hour_partition", "PerHourPartition") + + +# --- load balancers --------------------------------------------------------------------- + + +def _key_values(p: Props, cfn_name: str) -> list[tuple[str, Any]]: + """[{Key, Value}] attributes as pairs. A computed list is reported and skipped.""" + raw = p.take(cfn_name) + if raw is None: + return [] + if not isinstance(raw, list) or not all( + isinstance(item, dict) and isinstance(item.get("Key"), str) for item in raw + ): + p.ctx.note(f"{p.owner}: '{p.where}.{cfn_name}' is computed and was not converted") + p.comment(f"{cfn_name} was not converted (computed)") + return [] + return [(item["Key"], item.get("Value")) for item in raw] + + +def _unknown_attribute(p: Props, cfn_name: str, key: str, value: Any) -> None: + """Report an attribute key the converter does not know, and keep it as a comment.""" + p.ctx.note(f"{p.owner}: {cfn_name} '{key}' was not converted; set it by hand") + p.comment(f"{cfn_name} {snippet(key)} = {hcl.inline(p.ctx.expr(value))} was not converted") + + +class LoadBalancer(ResourceConverter): + """AWS::ElasticLoadBalancingV2::LoadBalancer as aws_lb.""" + + cfn_type = "AWS::ElasticLoadBalancingV2::LoadBalancer" + tf_type = "aws_lb" + ref = "arn" + attrs: ClassVar[dict[str, str]] = { + "CanonicalHostedZoneID": "zone_id", + "DNSName": "dns_name", + "LoadBalancerArn": "arn", + "LoadBalancerFullName": "arn_suffix", + "LoadBalancerName": "name", + "SecurityGroups": "security_groups", + } + # LoadBalancerAttributes keys -> (attribute, kind); kind is "bool", "number" or "string". + attributes: ClassVar[dict[str, tuple[str, str]]] = { + "deletion_protection.enabled": ("enable_deletion_protection", "bool"), + "idle_timeout.timeout_seconds": ("idle_timeout", "number"), + "routing.http2.enabled": ("enable_http2", "bool"), + "routing.http.drop_invalid_header_fields.enabled": ("drop_invalid_header_fields", "bool"), + "routing.http.desync_mitigation_mode": ("desync_mitigation_mode", "string"), + "routing.http.preserve_host_header.enabled": ("preserve_host_header", "bool"), + "routing.http.xff_client_port.enabled": ("enable_xff_client_port", "bool"), + "routing.http.xff_header_processing.mode": ("xff_header_processing_mode", "string"), + "routing.http.x_amzn_tls_version_and_cipher_suite.enabled": ( + "enable_tls_version_and_cipher_suite_headers", + "bool", + ), + "load_balancing.cross_zone.enabled": ("enable_cross_zone_load_balancing", "bool"), + "waf.fail_open.enabled": ("enable_waf_fail_open", "bool"), + "client_keep_alive.seconds": ("client_keep_alive", "number"), + "zonal_shift.config.enabled": ("enable_zonal_shift", "bool"), + "dns_record.client_routing_policy": ("dns_record_client_routing_policy", "string"), + } + # Attribute key prefixes that become a log block. + logs: ClassVar[dict[str, str]] = { + "access_logs.s3.": "access_logs", + "connection_logs.s3.": "connection_logs", + "health_check_logs.s3.": "health_check_logs", + } + + def convert(self, b: Builder) -> None: + """The scheme, the network placement, the attributes and the log blocks.""" + p, ctx = b.props, b.ctx + p.attr("name", "Name") + p.attr("load_balancer_type", "Type") + scheme = p.take("Scheme") + if scheme is not None: + if isinstance(scheme, str): + p.set("internal", scheme == "internal") + else: + operand = wrap_operand(hcl.inline(ctx.expr(scheme))) + p.set("internal", Raw(f'{operand} == "internal"')) + p.attr("ip_address_type", "IpAddressType") + p.list_attr("subnets", "Subnets") + p.list_attr("security_groups", "SecurityGroups") + p.attr( + "enforce_security_group_inbound_rules_on_private_link_traffic", + "EnforceSecurityGroupInboundRulesOnPrivateLinkTraffic", + ) + self.add_attributes(p) + p.block("subnet_mapping", "SubnetMappings", self.fill_subnet_mapping) + p.tags() + + def add_attributes(self, p: Props) -> None: + """LoadBalancerAttributes as attributes and log blocks.""" + logs: dict[str, list[Attr]] = {} + for key, value in _key_values(p, "LoadBalancerAttributes"): + if key in self.attributes: + tf_name, kind = self.attributes[key] + p.set(tf_name, _typed(p, value, kind)) + continue + prefix = next((pre for pre in self.logs if key.startswith(pre)), None) + field = key[len(prefix) :] if prefix else "" + if prefix and field in ("enabled", "bucket", "prefix"): + kind = "bool" if field == "enabled" else "string" + logs.setdefault(self.logs[prefix], []).append(Attr(field, _typed(p, value, kind))) + continue + _unknown_attribute(p, "LoadBalancerAttributes", key, value) + for name, items in logs.items(): + if not any(item.name == "bucket" for item in items): + # The provider requires a bucket; with none, logging stays off as in AWS. + items.append(Attr("bucket", "")) + p.items.append(Block(name, [], sorted(items, key=attrgetter("name")))) + + def fill_subnet_mapping(self, m: Props) -> None: + """A subnet_mapping block.""" + m.attrs( + { + "subnet_id": "SubnetId", + "allocation_id": "AllocationId", + "private_ipv4_address": "PrivateIPv4Address", + "ipv6_address": "IPv6Address", + } + ) + + +class TargetGroup(ResourceConverter): + """AWS::ElasticLoadBalancingV2::TargetGroup as aws_lb_target_group, with + aws_lb_target_group_attachment resources for its targets.""" + + cfn_type = "AWS::ElasticLoadBalancingV2::TargetGroup" + tf_type = "aws_lb_target_group" + ref = "arn" + attrs: ClassVar[dict[str, str]] = { + "LoadBalancerArns": "load_balancer_arns", + "TargetGroupArn": "arn", + "TargetGroupFullName": "arn_suffix", + "TargetGroupName": "name", + } + # TargetGroupAttributes keys -> (attribute, kind), as in LoadBalancer.attributes. + attributes: ClassVar[dict[str, tuple[str, str]]] = { + "deregistration_delay.timeout_seconds": ("deregistration_delay", "string"), + "deregistration_delay.connection_termination.enabled": ("connection_termination", "bool"), + "slow_start.duration_seconds": ("slow_start", "number"), + "load_balancing.algorithm.type": ("load_balancing_algorithm_type", "string"), + "load_balancing.algorithm.anomaly_mitigation": ( + "load_balancing_anomaly_mitigation", + "string", + ), + "load_balancing.cross_zone.enabled": ("load_balancing_cross_zone_enabled", "string"), + "lambda.multi_value_headers.enabled": ("lambda_multi_value_headers_enabled", "bool"), + "proxy_protocol_v2.enabled": ("proxy_protocol_v2", "bool"), + "preserve_client_ip.enabled": ("preserve_client_ip", "string"), + } + # Attribute keys that go to the stickiness block. + stickiness: ClassVar[dict[str, tuple[str, str]]] = { + "stickiness.enabled": ("enabled", "bool"), + "stickiness.type": ("type", "string"), + "stickiness.lb_cookie.duration_seconds": ("cookie_duration", "number"), + "stickiness.app_cookie.duration_seconds": ("cookie_duration", "number"), + "stickiness.app_cookie.cookie_name": ("cookie_name", "string"), + } + # Properties that go to the health_check block. + health_check: ClassVar[dict[str, tuple[str, str]]] = { + "HealthCheckEnabled": ("enabled", "bool"), + "HealthCheckIntervalSeconds": ("interval", "number"), + "HealthCheckPath": ("path", "string"), + "HealthCheckPort": ("port", "string"), + "HealthCheckProtocol": ("protocol", "string"), + "HealthCheckTimeoutSeconds": ("timeout", "number"), + "HealthyThresholdCount": ("healthy_threshold", "number"), + "UnhealthyThresholdCount": ("unhealthy_threshold", "number"), + } + + def convert(self, b: Builder) -> None: + """The group, its attributes, health check and stickiness, and the targets.""" + p = b.props + p.attr("name", "Name") + p.number("port", "Port") + protocol = p.peek("Protocol") + target_type = p.peek("TargetType") + p.attr("protocol", "Protocol") + p.attr("protocol_version", "ProtocolVersion") + p.attr("vpc_id", "VpcId") + p.attr("target_type", "TargetType") + p.attr("ip_address_type", "IpAddressType") + stickiness = self.add_attributes(p) + health = self.health_items(p) + if health: + health.extend(self.health_check_defaults(health, protocol, target_type)) + p.items.append(Block("health_check", [], health)) + if stickiness: + # The provider turns stickiness on unless told otherwise; AWS leaves it off. + if not any(item.name == "enabled" for item in stickiness): + stickiness.insert(0, Attr("enabled", False)) + if not any(item.name == "type" for item in stickiness): + stickiness.append(Attr("type", "lb_cookie")) + p.items.append(Block("stickiness", [], stickiness)) + p.tags() + self.add_targets(b) + + def add_attributes(self, p: Props) -> list[Attr]: + """TargetGroupAttributes as attributes. Returns the items of the stickiness block.""" + attributes = _key_values(p, "TargetGroupAttributes") + sticky_type = dict(attributes).get("stickiness.type", "lb_cookie") + # Each cookie type has its own duration; Terraform has one cookie_duration. + duration = ( + "stickiness.app_cookie.duration_seconds" + if sticky_type == "app_cookie" + else "stickiness.lb_cookie.duration_seconds" + ) + stickiness: list[Attr] = [] + for key, value in attributes: + if key in self.attributes: + tf_name, kind = self.attributes[key] + p.set(tf_name, _typed(p, value, kind)) + elif key in self.stickiness and ( + not key.endswith(".duration_seconds") or key == duration + ): + tf_name, kind = self.stickiness[key] + stickiness.append(Attr(tf_name, _typed(p, value, kind))) + else: + _unknown_attribute(p, "TargetGroupAttributes", key, value) + return stickiness + + def health_items(self, p: Props) -> list[Any]: + """The items of the health_check block, from the HealthCheck* properties and + Matcher.""" + health: list[Any] = [] + for cfn_name, (tf_name, kind) in self.health_check.items(): + value = p.take(cfn_name) + if value is not None: + health.append(Attr(tf_name, _typed(p, value, kind))) + matcher = p.literal("Matcher", dict) + if matcher is not None: + code = matcher.get("HttpCode", matcher.get("GrpcCode")) + if code is not None: + health.append(Attr("matcher", p.ctx.expr(code))) + return health + + def health_check_defaults( + self, health: list[Any], protocol: Any, target_type: Any + ) -> list[Attr]: + """Settings the provider defaults differently from AWS, for a health_check block that + sets only some of them: thresholds (and interval for Lambda and GENEVE).""" + given = {item.name for item in health} + lambda_target = target_type == "lambda" + defaults = { + "healthy_threshold": 5, + "unhealthy_threshold": 5 if lambda_target else 2, + } + if lambda_target: + defaults["interval"] = 35 + elif protocol == "GENEVE": + defaults["interval"] = 10 + return [Attr(name, value) for name, value in defaults.items() if name not in given] + + def add_targets(self, b: Builder) -> None: + """Targets as aws_lb_target_group_attachment resources.""" + p, ctx = b.props, b.ctx + targets = p.take("Targets") + if isinstance(targets, list): + for number, target in enumerate(targets, start=1): + inner = Props(ctx, target, f"{b.logical_id}.Targets[{number - 1}]", p.owner) + inner.set("target_group_arn", b.self_ref("arn")) + inner.attr("target_id", "Id") + inner.number("port", "Port") + inner.attr("availability_zone", "AvailabilityZone") + inner.finish() + b.add_resource("aws_lb_target_group_attachment", f"_target_{number}", inner.items) + elif targets is not None: + ctx.note( + f"{b.logical_id}: Targets is computed and was not converted; attach them by hand" + ) + + +def _action(r: Props) -> None: + """A listener (rule) action as a default_action / action block.""" + r.attr("type", "Type") + r.number("order", "Order") + forward = r.peek("ForwardConfig") + if isinstance(forward, dict) and forward.get("TargetGroupStickinessConfig") is not None: + # Stickiness only exists in the forward block, and Terraform takes the group either + # there or in target_group_arn; CloudFormation lets both name the same one. + r.drop("TargetGroupArn") + elif r.attr("target_group_arn", "TargetGroupArn"): + r.drop("ForwardConfig") + r.block("forward", "ForwardConfig", _forward) + r.block("redirect", "RedirectConfig", _redirect) + r.block("fixed_response", "FixedResponseConfig", _fixed_response) + r.block("authenticate_cognito", "AuthenticateCognitoConfig", _cognito) + r.block("authenticate_oidc", "AuthenticateOidcConfig", _oidc) + + +def _forward(c: Props) -> None: + """The forward block of an action.""" + _blocks(c, "target_group", "TargetGroups", _forward_target_group) + c.block("stickiness", "TargetGroupStickinessConfig", _forward_stickiness) + + +def _forward_target_group(g: Props) -> None: + """A target_group block of a forward block.""" + g.attr("arn", "TargetGroupArn") + g.number("weight", "Weight") + + +def _forward_stickiness(s: Props) -> None: + """The stickiness block of a forward block.""" + s.boolean("enabled", "Enabled") + s.number("duration", "DurationSeconds") + + +def _redirect(c: Props) -> None: + """The redirect block of an action.""" + c.attrs( + { + "host": "Host", + "path": "Path", + "port": "Port", + "protocol": "Protocol", + "query": "Query", + "status_code": "StatusCode", + } + ) + + +def _fixed_response(c: Props) -> None: + """The fixed_response block of an action.""" + c.attrs( + { + "content_type": "ContentType", + "message_body": "MessageBody", + "status_code": "StatusCode", + } + ) + + +def _auth_common(c: Props) -> None: + """The settings Cognito and OIDC authentication share.""" + c.attr("authentication_request_extra_params", "AuthenticationRequestExtraParams") + c.attr("on_unauthenticated_request", "OnUnauthenticatedRequest") + c.attr("scope", "Scope") + c.attr("session_cookie_name", "SessionCookieName") + c.number("session_timeout", "SessionTimeout") + + +def _cognito(c: Props) -> None: + """The authenticate_cognito block of an action.""" + c.attrs( + { + "user_pool_arn": "UserPoolArn", + "user_pool_client_id": "UserPoolClientId", + "user_pool_domain": "UserPoolDomain", + } + ) + _auth_common(c) + + +def _oidc(c: Props) -> None: + """The authenticate_oidc block of an action.""" + c.attrs( + { + "authorization_endpoint": "AuthorizationEndpoint", + "client_id": "ClientId", + "client_secret": "ClientSecret", + "issuer": "Issuer", + "token_endpoint": "TokenEndpoint", + "user_info_endpoint": "UserInfoEndpoint", + } + ) + c.drop("UseExistingClientSecret") # Terraform always sends the secret it is given. + _auth_common(c) + + +def _certificate_arns(b: Builder) -> list[Any]: + """The ARNs in Certificates. A computed list is reported and skipped.""" + certificates = b.props.take("Certificates") + if certificates is None: + return [] + if not isinstance(certificates, list): + b.ctx.note(f"{b.logical_id}: Certificates is computed and was not converted") + return [] + return [ + c["CertificateArn"] for c in certificates if isinstance(c, dict) and "CertificateArn" in c + ] + + +def _extra_certificates(b: Builder, listener_arn: Any, arns: list[Any], start: int) -> None: + """aws_lb_listener_certificate resources for certificates after the first.""" + for number, arn in enumerate(arns, start=start): + b.add_resource( + "aws_lb_listener_certificate", + f"_certificate_{number}", + [Attr("listener_arn", listener_arn), Attr("certificate_arn", b.ctx.expr(arn))], + ) + + +class Listener(ResourceConverter): + """AWS::ElasticLoadBalancingV2::Listener as aws_lb_listener.""" + + cfn_type = "AWS::ElasticLoadBalancingV2::Listener" + tf_type = "aws_lb_listener" + ref = "arn" + attrs: ClassVar[dict[str, str]] = {"ListenerArn": "arn"} + + def convert(self, b: Builder) -> None: + """The port, TLS settings, certificates and default actions.""" + p = b.props + p.attr("load_balancer_arn", "LoadBalancerArn") + p.number("port", "Port") + p.attr("protocol", "Protocol") + p.attr("ssl_policy", "SslPolicy") + alpn = p.take("AlpnPolicy") + if alpn is not None: + # A list of one in CloudFormation, a string in Terraform. + p.set("alpn_policy", b.ctx.expr(alpn[0] if isinstance(alpn, list) and alpn else alpn)) + arns = _certificate_arns(b) + if arns: + # The listener holds the default certificate; the others are attached separately. + p.set("certificate_arn", b.ctx.expr(arns[0])) + _extra_certificates(b, b.self_ref("arn"), arns[1:], start=2) + p.block("default_action", "DefaultActions", _action) + + +class ListenerCertificate(ResourceConverter): + """AWS::ElasticLoadBalancingV2::ListenerCertificate as aws_lb_listener_certificate, one + resource per certificate.""" + + cfn_type = "AWS::ElasticLoadBalancingV2::ListenerCertificate" + tf_type = "aws_lb_listener_certificate" + + def convert(self, b: Builder) -> None: + """The listener and the first certificate; the others become resources of their + own.""" + listener_arn = b.ctx.expr(b.props.take("ListenerArn")) + arns = _certificate_arns(b) + b.props.set("listener_arn", listener_arn) + if arns: + b.props.set("certificate_arn", b.ctx.expr(arns[0])) + _extra_certificates(b, listener_arn, arns[1:], start=2) + + +class ListenerRule(ResourceConverter): + """AWS::ElasticLoadBalancingV2::ListenerRule as aws_lb_listener_rule.""" + + cfn_type = "AWS::ElasticLoadBalancingV2::ListenerRule" + tf_type = "aws_lb_listener_rule" + ref = "arn" + attrs: ClassVar[dict[str, str]] = {"RuleArn": "arn"} + # Condition Field -> (Terraform block, CloudFormation configuration property). + condition_configs: ClassVar[dict[str, tuple[str, str]]] = { + "path-pattern": ("path_pattern", "PathPatternConfig"), + "host-header": ("host_header", "HostHeaderConfig"), + "http-header": ("http_header", "HttpHeaderConfig"), + "http-request-method": ("http_request_method", "HttpRequestMethodConfig"), + "query-string": ("query_string", "QueryStringConfig"), + "source-ip": ("source_ip", "SourceIpConfig"), + } + + def convert(self, b: Builder) -> None: + """The listener, the priority, actions, conditions and tags.""" + p = b.props + p.attr("listener_arn", "ListenerArn") + p.number("priority", "Priority") + p.block("action", "Actions", _action) + p.block("condition", "Conditions", self.fill_condition) + p.tags() + + def fill_condition(self, c: Props) -> None: + """A condition block.""" + field = c.take("Field") + legacy = c.take("Values") + if not isinstance(field, str) or field not in self.condition_configs: + c.ctx.note(f"{c.owner}: rule condition '{field}' was not converted; set it by hand") + c.comment(f"Condition on {snippet(field)} was not converted") + return + tf_name, cfn_name = self.condition_configs[field] + config = c.literal(cfn_name, dict) or {} + if field == "query-string": + pairs = c.literal("Values", list, value=config.get("Values")) or [] + c.add_blocks(tf_name, pairs, self.fill_query_string, f"{c.where}.{cfn_name}.Values") + return + items: list[Any] = [] + if config.get("HttpHeaderName") is not None: + items.append(Attr("http_header_name", c.ctx.expr(config["HttpHeaderName"]))) + values = config.get("Values", legacy) + if values is not None: + items.append(Attr("values", _as_list(c.ctx, values))) + if config.get("RegexValues") is not None: + items.append(Attr("regex_values", _as_list(c.ctx, config["RegexValues"]))) + c.items.append(Block(tf_name, [], items)) + + def fill_query_string(self, q: Props) -> None: + """A query_string block of a condition.""" + q.attr("key", "Key") + q.attr("value", "Value") + + +# --- Route 53 --------------------------------------------------------------------------- + + +class HostedZone(ResourceConverter): + """AWS::Route53::HostedZone as aws_route53_zone.""" + + cfn_type = "AWS::Route53::HostedZone" + tf_type = "aws_route53_zone" + attrs: ClassVar[dict[str, str]] = {"Id": "zone_id", "NameServers": "name_servers"} + + def convert(self, b: Builder) -> None: + """The name, the comment, the VPCs of a private zone and tags.""" + p = b.props + p.attr("name", "Name") + config = p.literal("HostedZoneConfig", dict) or {} + # The default comment of the provider is "Managed by Terraform"; CloudFormation sets + # none. + comment = config.get("Comment") + p.set("comment", "" if comment is None else b.ctx.expr(comment)) + p.block("vpc", "VPCs", self.fill_vpc) + p.tags("HostedZoneTags") + + def fill_vpc(self, v: Props) -> None: + """A vpc block.""" + v.attrs({"vpc_id": "VPCId", "vpc_region": "VPCRegion"}) + + +def _zone_name(value: Any) -> str | None: + """A literal zone name in the form names are compared in, else None.""" + return value.rstrip(".").lower() if isinstance(value, str) else None + + +class RecordSet(ResourceConverter): + """AWS::Route53::RecordSet as aws_route53_record.""" + + cfn_type = "AWS::Route53::RecordSet" + tf_type = "aws_route53_record" + ref = "fqdn" + + def convert(self, b: Builder) -> None: + """The one record.""" + self.record(b, b.props) + + def record(self, b: Builder, p: Props) -> None: + """One record set's properties `p` as aws_route53_record items.""" + ctx = b.ctx + self.zone_id(b, p) + p.attr("name", "Name") + p.attr("type", "Type") + p.number("ttl", "TTL") + p.list_attr("records", "ResourceRecords") + p.attr("set_identifier", "SetIdentifier") + p.attr("health_check_id", "HealthCheckId") + p.boolean("multivalue_answer_routing_policy", "MultiValueAnswer") + p.drop("Comment") # A Route 53 change comment; Terraform has no counterpart. + alias = p.take("AliasTarget") + if isinstance(alias, dict): + evaluate = p.as_bool(alias.get("EvaluateTargetHealth", False)) + p.items.append( + Block( + "alias", + [], + [ + Attr("name", ctx.expr(alias.get("DNSName"))), + Attr("zone_id", ctx.expr(alias.get("HostedZoneId"))), + Attr("evaluate_target_health", evaluate), + ], + ) + ) + for cfn_name, block, tf_name, number in ( + ("Weight", "weighted_routing_policy", "weight", True), + ("Region", "latency_routing_policy", "region", False), + ("Failover", "failover_routing_policy", "type", False), + ): + value = p.take(cfn_name) + if value is not None: + converted = p.as_number(value) if number else ctx.expr(value) + p.items.append(Block(block, [], [Attr(tf_name, converted)])) + p.block("geolocation_routing_policy", "GeoLocation", self.fill_geolocation) + + def fill_geolocation(self, g: Props) -> None: + """The geolocation_routing_policy block.""" + g.attrs( + { + "continent": "ContinentCode", + "country": "CountryCode", + "subdivision": "SubdivisionCode", + } + ) + + def zone_id(self, b: Builder, p: Props) -> None: + """zone_id from HostedZoneId, or from HostedZoneName: a hosted zone of the same + template when one has that name, a data source lookup otherwise.""" + if p.attr("zone_id", "HostedZoneId"): + p.drop("HostedZoneName") + return + name = p.take("HostedZoneName") + if name is None: + return + wanted = _zone_name(name) + for logical_id, other in (b.ctx.template.get("Resources") or {}).items(): + if other.get("Type") != "AWS::Route53::HostedZone" or wanted is None: + continue + if _zone_name((other.get("Properties") or {}).get("Name")) == wanted: + p.set("zone_id", b.ctx.ref(logical_id)) + return + data_name = f"{b.info.name}_zone" + if not any(block.type == "data" and block.labels[1] == data_name for block in b.extra): + b.add_data("aws_route53_zone", "_zone", [Attr("name", b.ctx.expr(name))]) + index = "[0]" if b.resource.get("Condition") else "" + p.set("zone_id", Raw(f"data.aws_route53_zone.{data_name}{index}.zone_id")) + + +class RecordSetGroup(RecordSet): + """AWS::Route53::RecordSetGroup as aws_route53_record resources.""" + + cfn_type = "AWS::Route53::RecordSetGroup" + + def convert(self, b: Builder) -> None: + """The first record is the main resource; each other record is a resource of its + own.""" + p = b.props + zone: dict[str, Any] = {} + for name in ("HostedZoneId", "HostedZoneName"): + value = p.take(name) + if value is not None: + zone[name] = value + p.drop("Comment") + records = p.take("RecordSets") + if not isinstance(records, list) or not records: + b.ctx.note(f"{b.logical_id}: RecordSets is empty or computed and was not converted") + return + for number, record in enumerate(records, start=1): + values: dict[str, Any] = {} + if isinstance(record, dict): + values = dict(zone) + values.update(record) + inner = Props(b.ctx, values, f"{b.logical_id}.RecordSets[{number - 1}]", p.owner) + self.record(b, inner) + inner.finish() + if number == 1: + p.items.extend(inner.items) + else: + b.add_resource("aws_route53_record", f"_{number}", inner.items) + + +# --- ACM -------------------------------------------------------------------------------- + + +def _dns_validated(resource: dict[str, Any]) -> bool: + """Whether CloudFormation creates the validation records itself: DNS validation with a + zone given.""" + properties = resource.get("Properties") or {} + options = properties.get("DomainValidationOptions") + return ( + properties.get("ValidationMethod") == "DNS" + and isinstance(options, list) + and any(isinstance(o, dict) and o.get("HostedZoneId") is not None for o in options) + ) + + +class Certificate(ResourceConverter): + """AWS::CertificateManager::Certificate as aws_acm_certificate, with the DNS validation + records and the wait for validation when CloudFormation handles those.""" + + cfn_type = "AWS::CertificateManager::Certificate" + tf_type = "aws_acm_certificate" + ref = "arn" + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """CloudFormation finishes the certificate only once it is validated; references + wait for the same thing through the validation resource.""" + if _dns_validated(resource): + index = "[0]" if info.conditional else "" + info.overrides["arn"] = ( + f"aws_acm_certificate_validation.{info.name}{index}.certificate_arn" + ) + + def convert(self, b: Builder) -> None: + """The names, the validation and the options.""" + p, ctx = b.props, b.ctx + p.attr("domain_name", "DomainName") + p.list_attr("subject_alternative_names", "SubjectAlternativeNames") + method = p.peek("ValidationMethod") + p.attr("validation_method", "ValidationMethod") + p.attr("key_algorithm", "KeyAlgorithm") + p.attr("certificate_authority_arn", "CertificateAuthorityArn") + logging = p.take("CertificateTransparencyLoggingPreference") + if logging is not None: + preference = Attr("certificate_transparency_logging_preference", ctx.expr(logging)) + p.items.append(Block("options", [], [preference])) + p.tags() + dns = _dns_validated(b.resource) + options = p.take("DomainValidationOptions") + zones: dict[str, Any] = {} + for option in options if isinstance(options, list) else []: + if not isinstance(option, dict): + continue + domain = option.get("DomainName") + if dns and option.get("HostedZoneId") is not None: + zones[str(domain)] = ctx.expr(option["HostedZoneId"]) + elif option.get("ValidationDomain") is not None and method != "DNS": + p.items.append( + Block( + "validation_option", + [], + [ + Attr("domain_name", ctx.expr(domain)), + Attr("validation_domain", ctx.expr(option["ValidationDomain"])), + ], + ) + ) + if dns: + self.validation_records(b, zones) + elif method == "DNS": + ctx.note( + f"{b.logical_id} is validated by DNS without a hosted zone: add the records from " + "domain_validation_options and an aws_acm_certificate_validation resource" + ) + + def validation_records(self, b: Builder, zones: dict[str, Any]) -> None: + """The DNS records and the wait that CloudFormation handles inside the certificate.""" + own = f"{b.info.address}[0]" if b.info.conditional else b.info.address + options = ( + f"flatten({b.info.address}[*].domain_validation_options)" + if b.info.conditional + else f"{b.info.address}.domain_validation_options" + ) + first = next(iter(zones.values())) + if len({hcl.inline(z) for z in zones.values()}) == 1: + zone: Any = first + else: + zone = Raw(f"lookup({hcl.inline(zones)}, each.key, {hcl.inline(first)})") + records = Raw( + f"{{ for option in {options} : option.domain_name => {{ name = " + "option.resource_record_name, record = option.resource_record_value, type = " + "option.resource_record_type } }" + ) + validation = f"aws_route53_record.{b.info.name}_validation" + b.add_resource( + "aws_route53_record", + "_validation", + [ + Attr("for_each", records), + BLANK, + Attr("allow_overwrite", True), + Attr("name", Raw("each.value.name")), + Attr("records", [Raw("each.value.record")]), + Attr("ttl", 60), + Attr("type", Raw("each.value.type")), + Attr("zone_id", zone), + ], + counted=False, + ) + b.add_resource( + "aws_acm_certificate_validation", + "", + [ + Attr("certificate_arn", Raw(f"{own}.arn")), + Attr("validation_record_fqdns", Raw(f"[for record in {validation} : record.fqdn]")), + ], + ) + + +# --- CloudFront ------------------------------------------------------------------------- + + +class Distribution(ResourceConverter): + """AWS::CloudFront::Distribution as aws_cloudfront_distribution.""" + + cfn_type = "AWS::CloudFront::Distribution" + tf_type = "aws_cloudfront_distribution" + attrs: ClassVar[dict[str, str]] = {"DomainName": "domain_name", "Id": "id"} + # The methods a cache behavior allows and caches when the template names none. + default_methods: ClassVar[list[str]] = ["GET", "HEAD"] + + def convert(self, b: Builder) -> None: + """DistributionConfig, flattened into the resource, and tags.""" + p = b.props + p.tags() + config = p.take("DistributionConfig") + if not isinstance(config, dict) or intrinsic_name(config) is not None: + b.ctx.note(f"{b.logical_id}: DistributionConfig is missing or computed; set it by hand") + return + c = Props(b.ctx, config, f"{b.logical_id}.DistributionConfig", p.owner) + c.boolean("enabled", "Enabled") + c.list_attr("aliases", "Aliases") + c.attr("comment", "Comment") + c.attr("default_root_object", "DefaultRootObject") + if not c.attr("http_version", "HttpVersion"): + c.set("http_version", "http1.1") # The CloudFormation default; the provider has http2 + c.boolean("is_ipv6_enabled", "IPV6Enabled") + c.attr("price_class", "PriceClass") + c.attr("web_acl_id", "WebACLId") + c.attr("continuous_deployment_policy_id", "ContinuousDeploymentPolicyId") + c.boolean("staging", "Staging") + c.block("origin", "Origins", self.fill_origin) + groups = c.take("OriginGroups") + if isinstance(groups, dict): + where = f"{c.where}.OriginGroups" + c.add_blocks("origin_group", groups.get("Items") or [], self.fill_origin_group, where) + c.block("default_cache_behavior", "DefaultCacheBehavior", self.fill_default_behavior) + c.block("ordered_cache_behavior", "CacheBehaviors", self.fill_ordered_behavior) + c.block("custom_error_response", "CustomErrorResponses", self.fill_error_response) + c.block("logging_config", "Logging", self.fill_logging) + # Terraform requires both blocks; these are the CloudFormation defaults when left out. + if not c.block("restrictions", "Restrictions", self.fill_restrictions): + geo = Block("geo_restriction", [], [Attr("restriction_type", "none")]) + c.items.append(Block("restrictions", [], [geo])) + if not c.block("viewer_certificate", "ViewerCertificate", self.fill_viewer_certificate): + default = Attr("cloudfront_default_certificate", True) + c.items.append(Block("viewer_certificate", [], [default])) + c.finish() + p.items.extend(c.items) + + def fill_error_response(self, r: Props) -> None: + """A custom_error_response block.""" + r.number("error_code", "ErrorCode") + r.number("response_code", "ResponseCode") + r.attr("response_page_path", "ResponsePagePath") + r.number("error_caching_min_ttl", "ErrorCachingMinTTL") + + def fill_logging(self, r: Props) -> None: + """The logging_config block.""" + r.attr("bucket", "Bucket") + r.boolean("include_cookies", "IncludeCookies") + r.attr("prefix", "Prefix") + + def fill_origin(self, r: Props) -> None: + """An origin block.""" + ctx = r.ctx + r.attr("domain_name", "DomainName") + r.attr("origin_id", "Id") + r.attr("origin_path", "OriginPath") + r.number("connection_attempts", "ConnectionAttempts") + r.number("connection_timeout", "ConnectionTimeout") + r.number("response_completion_timeout", "ResponseCompletionTimeout") + r.attr("origin_access_control_id", "OriginAccessControlId") + _blocks(r, "custom_header", "OriginCustomHeaders", self.fill_custom_header) + s3 = r.literal("S3OriginConfig", dict) + if s3 is not None: + identity = s3.get("OriginAccessIdentity") + # An empty identity is how CloudFormation says "use the origin access control". + if identity not in (None, ""): + access = Attr("origin_access_identity", ctx.expr(identity)) + r.items.append(Block("s3_origin_config", [], [access])) + if s3.get("OriginReadTimeout") is not None: + ctx.note( + f"{r.owner}: '{r.where}.S3OriginConfig.OriginReadTimeout' has no Terraform " + "counterpart for S3 origins and was not converted" + ) + r.block("custom_origin_config", "CustomOriginConfig", self.fill_custom_origin) + r.block("origin_shield", "OriginShield", self.fill_origin_shield) + r.block("vpc_origin_config", "VpcOriginConfig", self.fill_vpc_origin) + + def fill_custom_header(self, h: Props) -> None: + """A custom_header block of an origin.""" + h.attr("name", "HeaderName") + h.attr("value", "HeaderValue") + + def fill_origin_shield(self, s: Props) -> None: + """The origin_shield block of an origin.""" + s.boolean("enabled", "Enabled") + s.attr("origin_shield_region", "OriginShieldRegion") + + def fill_vpc_origin(self, v: Props) -> None: + """The vpc_origin_config block of an origin.""" + v.attr("vpc_origin_id", "VpcOriginId") + v.number("origin_keepalive_timeout", "OriginKeepaliveTimeout") + v.number("origin_read_timeout", "OriginReadTimeout") + v.attr("owner_account_id", "OwnerAccountId") + + def fill_custom_origin(self, c: Props) -> None: + """The custom_origin_config block of an origin.""" + # Ports and protocols are optional in CloudFormation but required by the provider. + if not c.number("http_port", "HTTPPort"): + c.set("http_port", 80) + if not c.number("https_port", "HTTPSPort"): + c.set("https_port", 443) + c.attr("origin_protocol_policy", "OriginProtocolPolicy") + if not c.list_attr("origin_ssl_protocols", "OriginSSLProtocols"): + c.set("origin_ssl_protocols", ["TLSv1.2"]) + c.ctx.note( + f"{c.owner}: '{c.where}' had no OriginSSLProtocols; Terraform requires them, so " + "TLSv1.2 was set" + ) + c.number("origin_read_timeout", "OriginReadTimeout") + c.number("origin_keepalive_timeout", "OriginKeepaliveTimeout") + c.attr("ip_address_type", "IpAddressType") + + def fill_origin_group(self, g: Props) -> None: + """An origin_group block.""" + g.attr("origin_id", "Id") + criteria = g.literal("FailoverCriteria", dict) or {} + codes = g.literal("FailoverCriteria.StatusCodes", dict, value=criteria.get("StatusCodes")) + items = g.literal("StatusCodes.Items", list, value=(codes or {}).get("Items")) or [] + status_codes = Attr("status_codes", [g.as_number(code) for code in items]) + g.items.append(Block("failover_criteria", [], [status_codes])) + members = g.literal("Members", dict) or {} + member_items = g.literal("Members.Items", list, value=members.get("Items")) or [] + g.add_blocks("member", member_items, self.fill_member, f"{g.where}.Members") + + def fill_member(self, m: Props) -> None: + """A member block of an origin group.""" + m.attr("origin_id", "OriginId") + + def methods(self, r: Props, tf_name: str, cfn_name: str) -> None: + """A list of methods, GET and HEAD when the template names none.""" + if not r.list_attr(tf_name, cfn_name): + r.set(tf_name, list(self.default_methods)) + + def fill_default_behavior(self, r: Props) -> None: + """The default_cache_behavior block.""" + self.behavior(r, ordered=False) + + def fill_ordered_behavior(self, r: Props) -> None: + """An ordered_cache_behavior block.""" + self.behavior(r, ordered=True) + + def behavior(self, r: Props, ordered: bool) -> None: + """A cache behavior block; an `ordered` one has a path pattern.""" + if ordered: + r.attr("path_pattern", "PathPattern") + self.methods(r, "allowed_methods", "AllowedMethods") + self.methods(r, "cached_methods", "CachedMethods") + r.attr("target_origin_id", "TargetOriginId") + r.attr("viewer_protocol_policy", "ViewerProtocolPolicy") + r.attr("cache_policy_id", "CachePolicyId") + r.attr("origin_request_policy_id", "OriginRequestPolicyId") + r.attr("response_headers_policy_id", "ResponseHeadersPolicyId") + r.boolean("compress", "Compress") + r.number("default_ttl", "DefaultTTL") + r.number("max_ttl", "MaxTTL") + r.number("min_ttl", "MinTTL") + r.attr("field_level_encryption_id", "FieldLevelEncryptionId") + r.attr("realtime_log_config_arn", "RealtimeLogConfigArn") + r.boolean("smooth_streaming", "SmoothStreaming") + r.list_attr("trusted_key_groups", "TrustedKeyGroups") + r.list_attr("trusted_signers", "TrustedSigners") + _blocks(r, "function_association", "FunctionAssociations", self.fill_function) + _blocks(r, "lambda_function_association", "LambdaFunctionAssociations", self.fill_lambda) + r.block("forwarded_values", "ForwardedValues", self.fill_forwarded_values) + + def fill_function(self, a: Props) -> None: + """A function_association block.""" + a.attr("event_type", "EventType") + a.attr("function_arn", "FunctionARN") + + def fill_lambda(self, a: Props) -> None: + """A lambda_function_association block.""" + a.attr("event_type", "EventType") + a.attr("lambda_arn", "LambdaFunctionARN") + a.boolean("include_body", "IncludeBody") + + def fill_forwarded_values(self, f: Props) -> None: + """The forwarded_values block, with the query_string and cookies the provider + requires.""" + if not f.boolean("query_string", "QueryString"): + f.set("query_string", False) + f.list_attr("headers", "Headers") + f.list_attr("query_string_cache_keys", "QueryStringCacheKeys") + if not f.block("cookies", "Cookies", self.fill_cookies): + # Required by the provider; "none" is the CloudFormation default. + f.items.append(Block("cookies", [], [Attr("forward", "none")])) + + def fill_cookies(self, c: Props) -> None: + """The cookies block of forwarded_values.""" + c.attr("forward", "Forward") + c.list_attr("whitelisted_names", "WhitelistedNames") + + def fill_restrictions(self, r: Props) -> None: + """The restrictions block.""" + r.block("geo_restriction", "GeoRestriction", self.fill_geo_restriction) + + def fill_geo_restriction(self, g: Props) -> None: + """The geo_restriction block of restrictions.""" + g.attr("restriction_type", "RestrictionType") + g.list_attr("locations", "Locations") + + def fill_viewer_certificate(self, v: Props) -> None: + """The viewer_certificate block.""" + v.attrs( + { + "acm_certificate_arn": "AcmCertificateArn", + "iam_certificate_id": "IamCertificateId", + "minimum_protocol_version": "MinimumProtocolVersion", + "ssl_support_method": "SslSupportMethod", + } + ) + v.boolean("cloudfront_default_certificate", "CloudFrontDefaultCertificate") + + +class OriginAccessControl(ResourceConverter): + """AWS::CloudFront::OriginAccessControl as aws_cloudfront_origin_access_control.""" + + cfn_type = "AWS::CloudFront::OriginAccessControl" + tf_type = "aws_cloudfront_origin_access_control" + attrs: ClassVar[dict[str, str]] = {"Id": "id"} + + def convert(self, b: Builder) -> None: + """OriginAccessControlConfig, flattened into the resource.""" + _nested(b, "OriginAccessControlConfig", self.fill_config) + + def fill_config(self, c: Props) -> None: + """The attributes from OriginAccessControlConfig.""" + c.attrs( + { + "name": "Name", + "description": "Description", + "origin_access_control_origin_type": "OriginAccessControlOriginType", + "signing_behavior": "SigningBehavior", + "signing_protocol": "SigningProtocol", + } + ) + + +class OriginAccessIdentity(ResourceConverter): + """AWS::CloudFront::CloudFrontOriginAccessIdentity as + aws_cloudfront_origin_access_identity.""" + + cfn_type = "AWS::CloudFront::CloudFrontOriginAccessIdentity" + tf_type = "aws_cloudfront_origin_access_identity" + attrs: ClassVar[dict[str, str]] = {"Id": "id", "S3CanonicalUserId": "s3_canonical_user_id"} + + def convert(self, b: Builder) -> None: + """CloudFrontOriginAccessIdentityConfig, flattened into the resource.""" + _nested(b, "CloudFrontOriginAccessIdentityConfig", self.fill_config) + + def fill_config(self, c: Props) -> None: + """The comment from CloudFrontOriginAccessIdentityConfig.""" + c.attr("comment", "Comment") + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + Vpc, + Subnet, + InternetGateway, + EgressOnlyInternetGateway, + VpcGatewayAttachment, + RouteTable, + Route, + SubnetRouteTableAssociation, + Eip, + EipAssociation, + NatGateway, + VpcEndpoint, + SecurityGroup, + SecurityGroupIngress, + SecurityGroupEgress, + NetworkAcl, + NetworkAclEntry, + SubnetNetworkAclAssociation, + FlowLog, + LoadBalancer, + TargetGroup, + Listener, + ListenerCertificate, + ListenerRule, + HostedZone, + RecordSet, + RecordSetGroup, + Certificate, + Distribution, + OriginAccessControl, + OriginAccessIdentity, +) diff --git a/services/converter-api/converters/cfn/resources/observability.py b/services/converter-api/converters/cfn/resources/observability.py new file mode 100644 index 0000000..05400b9 --- /dev/null +++ b/services/converter-api/converters/cfn/resources/observability.py @@ -0,0 +1,198 @@ +"""CloudWatch Logs, alarms and dashboards.""" + +from __future__ import annotations + +from typing import Any + +from converters.cfn.builder import Builder, Props, tags_map +from converters.cfn.context import Context +from converters.cfn.expressions import intrinsic_name +from converters.cfn.models import Block, Call, ResourceInfo +from converters.cfn.resources.base import ResourceConverter +from converters.cfn.resources.messaging import sub_json + + +def _dimensions(ctx: Context, value: Any) -> Any: + """[{Name, Value}] (alarms) or [{Key, Value}] (metric filters) as a map.""" + if isinstance(value, list) and all(isinstance(d, dict) for d in value): + renamed = [{"Key": d.get("Name", d.get("Key")), "Value": d.get("Value")} for d in value] + return tags_map(ctx, renamed) + return tags_map(ctx, value) + + +def _dimensions_attr(p: Props) -> None: + """The Dimensions property, when present, as the dimensions map.""" + value = p.take("Dimensions") + if value is not None: + p.set("dimensions", _dimensions(p.ctx, value)) + + +class LogGroup(ResourceConverter): + """AWS::Logs::LogGroup as aws_cloudwatch_log_group.""" + + cfn_type = "AWS::Logs::LogGroup" + tf_type = "aws_cloudwatch_log_group" + ref = "name" + import_id = "LogGroupName" + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """The CloudFormation Arn of a log group ends in ':*' (it covers the log streams); + the arn of the provider has no suffix. IAM policies written for the former must + keep matching the streams.""" + index = "[0]" if info.conditional else "" + info.attrs["Arn"] = "arn_with_streams" + info.overrides["arn_with_streams"] = f'"${{{info.address}{index}.arn}}:*"' + + def convert(self, b: Builder) -> None: + """The log group settings.""" + p = b.props + p.attr("name", "LogGroupName") + p.number("retention_in_days", "RetentionInDays") + p.attr("kms_key_id", "KmsKeyId") + p.attr("log_group_class", "LogGroupClass") + p.boolean("deletion_protection_enabled", "DeletionProtectionEnabled") + p.tags() + + +class LogMetricFilter(ResourceConverter): + """AWS::Logs::MetricFilter as aws_cloudwatch_log_metric_filter.""" + + cfn_type = "AWS::Logs::MetricFilter" + tf_type = "aws_cloudwatch_log_metric_filter" + ref = "name" + + def convert(self, b: Builder) -> None: + """The filter and its metric transformation.""" + p = b.props + b.name_attr("name", "FilterName") + p.attr("log_group_name", "LogGroupName") + p.attr("pattern", "FilterPattern") + p.boolean("apply_on_transformed_logs", "ApplyOnTransformedLogs") + # CloudFormation takes a list but allows exactly one transformation, as does Terraform. + p.block("metric_transformation", "MetricTransformations", self.fill_transformation) + + def fill_transformation(self, m: Props) -> None: + """The metric_transformation block. The default value is text in Terraform.""" + m.attr("name", "MetricName") + m.attr("namespace", "MetricNamespace") + m.attr("value", "MetricValue") + default = m.take("DefaultValue") + if default is not None: + text = str(default) if isinstance(default, int | float) else m.ctx.expr(default) + m.set("default_value", text) + m.attr("unit", "Unit") + _dimensions_attr(m) + + +class LogSubscriptionFilter(ResourceConverter): + """AWS::Logs::SubscriptionFilter as aws_cloudwatch_log_subscription_filter.""" + + cfn_type = "AWS::Logs::SubscriptionFilter" + tf_type = "aws_cloudwatch_log_subscription_filter" + ref = "name" + + def convert(self, b: Builder) -> None: + """The filter settings.""" + p = b.props + b.name_attr("name", "FilterName") + p.attr("log_group_name", "LogGroupName") + p.attr("filter_pattern", "FilterPattern") + p.attr("destination_arn", "DestinationArn") + p.attr("role_arn", "RoleArn") + p.attr("distribution", "Distribution") + p.boolean("apply_on_transformed_logs", "ApplyOnTransformedLogs") + p.list_attr("emit_system_fields", "EmitSystemFields") + + +class CloudWatchAlarm(ResourceConverter): + """AWS::CloudWatch::Alarm as aws_cloudwatch_metric_alarm.""" + + cfn_type = "AWS::CloudWatch::Alarm" + tf_type = "aws_cloudwatch_metric_alarm" + ref = "alarm_name" + attrs = {"Arn": "arn"} + import_id = "AlarmName" + + def convert(self, b: Builder) -> None: + """The alarm settings and its metric queries.""" + p = b.props + b.name_attr("alarm_name", "AlarmName") + p.attr("alarm_description", "AlarmDescription") + p.boolean("actions_enabled", "ActionsEnabled") + p.list_attr("alarm_actions", "AlarmActions") + p.list_attr("ok_actions", "OKActions") + p.list_attr("insufficient_data_actions", "InsufficientDataActions") + p.attr("comparison_operator", "ComparisonOperator") + p.number("evaluation_periods", "EvaluationPeriods") + p.number("datapoints_to_alarm", "DatapointsToAlarm") + p.attr("metric_name", "MetricName") + p.attr("namespace", "Namespace") + p.number("period", "Period") + p.attr("statistic", "Statistic") + p.attr("extended_statistic", "ExtendedStatistic") + p.number("threshold", "Threshold") + p.attr("threshold_metric_id", "ThresholdMetricId") + p.attr("treat_missing_data", "TreatMissingData") + p.attr("unit", "Unit") + p.attr("evaluate_low_sample_count_percentiles", "EvaluateLowSampleCountPercentile") + _dimensions_attr(p) + p.block("metric_query", "Metrics", self.fill_metric_query) + p.tags() + + def fill_metric_query(self, q: Props) -> None: + """One metric_query block, with MetricStat as its metric block.""" + q.attr("id", "Id") + q.attr("expression", "Expression") + q.attr("label", "Label") + q.boolean("return_data", "ReturnData") + q.number("period", "Period") + q.attr("account_id", "AccountId") + stat = q.literal("MetricStat", dict) + if stat is None: + return + inner = Props(q.ctx, stat, f"{q.where}.MetricStat", q.owner) + metric = inner.literal("Metric", dict) + if metric is not None: + if "MetricName" in metric: + inner.set("metric_name", q.ctx.expr(metric["MetricName"])) + if "Namespace" in metric: + inner.set("namespace", q.ctx.expr(metric["Namespace"])) + if metric.get("Dimensions"): + inner.set("dimensions", _dimensions(q.ctx, metric["Dimensions"])) + inner.number("period", "Period") + inner.attr("stat", "Stat") + inner.attr("unit", "Unit") + inner.finish() + q.items.append(Block("metric", [], inner.items)) + + +class CloudWatchDashboard(ResourceConverter): + """AWS::CloudWatch::Dashboard as aws_cloudwatch_dashboard.""" + + cfn_type = "AWS::CloudWatch::Dashboard" + tf_type = "aws_cloudwatch_dashboard" + ref = "dashboard_name" + import_id = "DashboardName" + + def convert(self, b: Builder) -> None: + """The dashboard, with a `!Sub` JSON body as a jsonencode() structure.""" + p = b.props + b.name_attr("dashboard_name", "DashboardName") + body = p.peek("DashboardBody") + parsed = ( + sub_json(body) if isinstance(body, dict) and intrinsic_name(body) == "Fn::Sub" else None + ) + if parsed is not None: + p.drop("DashboardBody") + p.set("dashboard_body", Call("jsonencode", b.ctx.expr(parsed))) + else: + p.json("dashboard_body", "DashboardBody") + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + LogGroup, + LogMetricFilter, + LogSubscriptionFilter, + CloudWatchAlarm, + CloudWatchDashboard, +) diff --git a/services/converter-api/converters/cfn/resources/registry.py b/services/converter-api/converters/cfn/resources/registry.py new file mode 100644 index 0000000..62017ec --- /dev/null +++ b/services/converter-api/converters/cfn/resources/registry.py @@ -0,0 +1,40 @@ +"""Which hand-written converter handles which CloudFormation type.""" + +from __future__ import annotations + +from converters.cfn.resources import ( + apigateway, + compute, + data, + iam, + messaging, + network, + observability, + storage, +) +from converters.cfn.resources.base import ResourceConverter + + +class ResourceRegistry: + """The hand-written converters, by CloudFormation type. A type without one is + converted with the awscc provider.""" + + def __init__(self, converters: tuple[type[ResourceConverter], ...]) -> None: + """One instance of each converter class.""" + self.by_type = {converter.cfn_type: converter() for converter in converters} + + def get(self, cfn_type: str) -> ResourceConverter | None: + """The converter for `cfn_type`, or None.""" + return self.by_type.get(cfn_type) + + +REGISTRY = ResourceRegistry( + apigateway.CONVERTERS + + compute.CONVERTERS + + data.CONVERTERS + + iam.CONVERTERS + + messaging.CONVERTERS + + network.CONVERTERS + + observability.CONVERTERS + + storage.CONVERTERS +) diff --git a/services/converter-api/converters/cfn/resources/storage.py b/services/converter-api/converters/cfn/resources/storage.py new file mode 100644 index 0000000..c8bb06d --- /dev/null +++ b/services/converter-api/converters/cfn/resources/storage.py @@ -0,0 +1,775 @@ +"""S3, DynamoDB and ECR.""" + +from __future__ import annotations + +from typing import Any, ClassVar + +from converters.cfn import hcl +from converters.cfn.builder import Builder, Props +from converters.cfn.expressions import intrinsic_name, wrap_operand +from converters.cfn.models import BLANK, Attr, Block, Raw, ResourceInfo +from converters.cfn.resources.base import ResourceConverter +from converters.cfn.resources.compute import literal_bool, optional_block + + +def sub_props(b: Builder, value: Any, name: str) -> Props: + """The properties of the nested structure `name` of the resource.""" + return Props(b.ctx, value, f"{b.logical_id}.{name}", b.props.owner) + + +def bucket_items(b: Builder) -> list[Any]: + """The `bucket = ...` line every bucket configuration resource starts with.""" + return [Attr("bucket", b.self_ref("id"))] + + +def optional_structure(r: Props, name: str, value: Any) -> tuple[str | None, Any]: + """A structure, or `!If [C, {...}, !Ref AWS::NoValue]` as (condition, structure). Other + functions are noted and give (None, None).""" + when, value = r.ctx.optional_item(value) + return when, r.literal(name, dict, value=value) + + +def structure_entries(r: Props, many: str, one: str) -> list[tuple[str | None, Any]]: + """The structures of a list property plus its single-item form (Transitions and the + older Transition), each with the condition it exists under.""" + values = list(r.literal(many, list) or []) + single = r.take(one) + if single is not None: + values.append(single) + entries = [optional_structure(r, many, value) for value in values] + return [(when, value) for when, value in entries if value is not None] + + +def fill_on_demand_throughput(o: Props) -> None: + """The on_demand_throughput block of a table or a global secondary index.""" + o.number("max_read_request_units", "MaxReadRequestUnits") + o.number("max_write_request_units", "MaxWriteRequestUnits") + + +# --- S3 --------------------------------------------------------------------------------- + + +class LifecycleRules: + """Fills the rule blocks of one lifecycle configuration, numbering them for the rules + that have no Id.""" + + def __init__(self) -> None: + """No rule filled yet.""" + self.number = 0 + + def fill(self, r: Props) -> None: + """One lifecycle rule.""" + self.number += 1 + if not r.attr("id", "Id"): + r.set("id", f"rule-{self.number}") + r.attr("status", "Status") + self.filter(r) + self.abort_incomplete_upload(r) + self.expiration(r) + self.transitions(r) + self.noncurrent_expiration(r) + self.noncurrent_transitions(r) + + def filter(self, r: Props) -> None: + """The filter block, built from the prefix, size and tag conditions.""" + prefix = r.take("Prefix") + tags = [ + tag + for tag in (r.literal("TagFilters", list) or []) + if r.literal("TagFilters", dict, value=tag) is not None + ] + greater = r.take("ObjectSizeGreaterThan") + less = r.take("ObjectSizeLessThan") + conditions = [x for x in (prefix, greater, less) if x is not None] + (tags or []) + filter_items: list[Any] = [] + if len(conditions) > 1: + inner: list[Any] = [] + if prefix is not None: + inner.append(Attr("prefix", r.ctx.expr(prefix))) + if greater is not None: + inner.append(Attr("object_size_greater_than", r.ctx.expr(greater))) + if less is not None: + inner.append(Attr("object_size_less_than", r.ctx.expr(less))) + if tags: + inner.append( + Attr("tags", {str(t.get("Key")): r.ctx.expr(t.get("Value")) for t in tags}) + ) + filter_items.append(Block("and", [], inner)) + elif prefix is not None: + filter_items.append(Attr("prefix", r.ctx.expr(prefix))) + elif greater is not None: + filter_items.append(Attr("object_size_greater_than", r.ctx.expr(greater))) + elif less is not None: + filter_items.append(Attr("object_size_less_than", r.ctx.expr(less))) + elif tags: + tag = tags[0] + filter_items.append( + Block( + "tag", + [], + [ + Attr("key", r.ctx.expr(tag.get("Key"))), + Attr("value", r.ctx.expr(tag.get("Value"))), + ], + ) + ) + # An empty filter means the whole bucket; the provider wants it spelled out. + r.items.append(Block("filter", [], filter_items)) + + def abort_incomplete_upload(self, r: Props) -> None: + """The abort_incomplete_multipart_upload block.""" + name = "AbortIncompleteMultipartUpload" + when, abort = optional_structure(r, name, r.take(name)) + if abort is None: + return + r.items.append( + optional_block( + "abort_incomplete_multipart_upload", + [Attr("days_after_initiation", r.ctx.expr(abort.get("DaysAfterInitiation")))], + when, + ) + ) + + def expiration(self, r: Props) -> None: + """The expiration block, from the three expiration properties.""" + expiration: list[Any] = [] + days = r.take("ExpirationInDays") + if days is not None: + expiration.append(Attr("days", r.ctx.expr(days))) + date = r.take("ExpirationDate") + if date is not None: + expiration.append(Attr("date", r.ctx.expr(date))) + marker = r.take("ExpiredObjectDeleteMarker") + if marker is not None: + expiration.append(Attr("expired_object_delete_marker", literal_bool(marker))) + if expiration: + r.items.append(Block("expiration", [], expiration)) + + def transitions(self, r: Props) -> None: + """One transition block per transition.""" + for when, transition in structure_entries(r, "Transitions", "Transition"): + items = [Attr("storage_class", r.ctx.expr(transition.get("StorageClass")))] + if "TransitionInDays" in transition: + items.insert(0, Attr("days", r.ctx.expr(transition["TransitionInDays"]))) + if "TransitionDate" in transition: + items.insert(0, Attr("date", r.ctx.expr(transition["TransitionDate"]))) + r.items.append(optional_block("transition", items, when)) + + def noncurrent_expiration(self, r: Props) -> None: + """The noncurrent_version_expiration block, from the old and the new property.""" + noncurrent_days = r.take("NoncurrentVersionExpirationInDays") + name = "NoncurrentVersionExpiration" + when, noncurrent = optional_structure(r, name, r.take(name)) + if noncurrent_days is None and noncurrent is None: + return + items = [] + if noncurrent is not None: + noncurrent_days = noncurrent.get("NoncurrentDays", noncurrent_days) + if "NewerNoncurrentVersions" in noncurrent: + items.append( + Attr( + "newer_noncurrent_versions", + r.ctx.expr(noncurrent["NewerNoncurrentVersions"]), + ) + ) + items.insert(0, Attr("noncurrent_days", r.ctx.expr(noncurrent_days))) + r.items.append(optional_block("noncurrent_version_expiration", items, when)) + + def noncurrent_transitions(self, r: Props) -> None: + """One noncurrent_version_transition block per noncurrent transition.""" + for when, transition in structure_entries( + r, "NoncurrentVersionTransitions", "NoncurrentVersionTransition" + ): + items = [ + Attr("noncurrent_days", r.ctx.expr(transition.get("TransitionInDays"))), + Attr("storage_class", r.ctx.expr(transition.get("StorageClass"))), + ] + if "NewerNoncurrentVersions" in transition: + items.append( + Attr( + "newer_noncurrent_versions", + r.ctx.expr(transition["NewerNoncurrentVersions"]), + ) + ) + r.items.append(optional_block("noncurrent_version_transition", items, when)) + + +class NotificationTarget: + """Fills the notification blocks of one kind of target (Lambda function, queue or topic).""" + + def __init__(self, target_attr: str, target_key: str) -> None: + """Targets read from `target_key` ("Queue") into `target_attr` ("queue_arn").""" + self.target_attr = target_attr + self.target_key = target_key + + def fill(self, r: Props) -> None: + """One notification: its events, target and key filters.""" + r.list_attr("events", "Event") + r.attr(self.target_attr, self.target_key) + filters = r.literal("Filter", dict) or {} + key = r.literal("Filter.S3Key", dict, value=filters.get("S3Key")) or {} + for rule in r.literal("Filter.S3Key.Rules", list, value=key.get("Rules")) or []: + literal_rule = r.literal("Filter.S3Key.Rules", dict, value=rule) + if literal_rule is None: + continue + name = str(literal_rule.get("Name", "")).lower() + if name in ("prefix", "suffix"): + r.set(f"filter_{name}", r.ctx.expr(literal_rule.get("Value"))) + + +class S3Bucket(ResourceConverter): + """AWS::S3::Bucket as one aws_s3_bucket plus one resource per configuration, as provider + v4+ requires.""" + + cfn_type = "AWS::S3::Bucket" + tf_type = "aws_s3_bucket" + attrs = { + "Arn": "arn", + "DomainName": "bucket_domain_name", + "RegionalDomainName": "bucket_regional_domain_name", + } + import_id = "BucketName" + canned_acl: ClassVar[dict[str, str]] = { + "Private": "private", + "PublicRead": "public-read", + "PublicReadWrite": "public-read-write", + "AuthenticatedRead": "authenticated-read", + "LogDeliveryWrite": "log-delivery-write", + "BucketOwnerRead": "bucket-owner-read", + "BucketOwnerFullControl": "bucket-owner-full-control", + "AwsExecRead": "aws-exec-read", + } + public_access: ClassVar[tuple[tuple[str, str], ...]] = ( + ("block_public_acls", "BlockPublicAcls"), + ("block_public_policy", "BlockPublicPolicy"), + ("ignore_public_acls", "IgnorePublicAcls"), + ("restrict_public_buckets", "RestrictPublicBuckets"), + ) + notification_targets: ClassVar[tuple[tuple[str, str, str, str], ...]] = ( + ("lambda_function", "LambdaConfigurations", "lambda_function_arn", "Function"), + ("queue", "QueueConfigurations", "queue_arn", "Queue"), + ("topic", "TopicConfigurations", "topic_arn", "Topic"), + ) + + def prepare(self, info: ResourceInfo, resource: dict[str, Any]) -> None: + """WebsiteURL lives on the separate website configuration resource.""" + index = "[0]" if info.conditional else "" + website = f"aws_s3_bucket_website_configuration.{info.name}_website{index}" + info.attrs["WebsiteURL"] = "website_url" + info.overrides["website_url"] = f'"http://${{{website}.website_endpoint}}"' + + def convert(self, b: Builder) -> None: + """The bucket, then its configuration resources.""" + p = b.props + p.attr("bucket", "BucketName") + p.boolean("object_lock_enabled", "ObjectLockEnabled") + if b.hints.get("force_destroy"): + p.set("force_destroy", True) + p.tags() + self.versioning(b) + self.encryption(b) + self.public_access_block(b) + self.access_control(b, self.ownership_controls(b)) + self.lifecycle(b) + self.cors(b) + self.website(b) + self.logging(b) + self.accelerate(b) + self.object_lock(b) + self.notification(b) + + def versioning(self, b: Builder) -> None: + """VersioningConfiguration as aws_s3_bucket_versioning.""" + versioning = b.props.take("VersioningConfiguration") + if versioning is None: + return + inner = sub_props(b, versioning, "VersioningConfiguration") + inner.attr("status", "Status") + inner.finish() + b.add_resource( + "aws_s3_bucket_versioning", + "_versioning", + bucket_items(b) + [Block("versioning_configuration", [], inner.items)], + ) + + def encryption(self, b: Builder) -> None: + """BucketEncryption as aws_s3_bucket_server_side_encryption_configuration.""" + encryption = b.props.take("BucketEncryption") + if encryption is None: + return + inner = sub_props(b, encryption, "BucketEncryption") + inner.block("rule", "ServerSideEncryptionConfiguration", self.fill_encryption_rule) + inner.finish() + b.add_resource( + "aws_s3_bucket_server_side_encryption_configuration", + "_encryption", + bucket_items(b) + inner.items, + ) + + def fill_encryption_rule(self, r: Props) -> None: + """One server side encryption rule.""" + r.boolean("bucket_key_enabled", "BucketKeyEnabled") + r.block( + "apply_server_side_encryption_by_default", + "ServerSideEncryptionByDefault", + self.fill_encryption_default, + ) + + def fill_encryption_default(self, d: Props) -> None: + """The default encryption of a rule.""" + d.attrs({"sse_algorithm": "SSEAlgorithm", "kms_master_key_id": "KMSMasterKeyID"}) + + def public_access_block(self, b: Builder) -> None: + """PublicAccessBlockConfiguration as aws_s3_bucket_public_access_block.""" + public = b.props.take("PublicAccessBlockConfiguration") + if public is None: + return + inner = sub_props(b, public, "PublicAccessBlockConfiguration") + for tf_name, cfn_name in self.public_access: + inner.boolean(tf_name, cfn_name) + inner.finish() + b.add_resource( + "aws_s3_bucket_public_access_block", "_public_access", bucket_items(b) + inner.items + ) + + def ownership_controls(self, b: Builder) -> str | None: + """OwnershipControls as aws_s3_bucket_ownership_controls. Returns its address.""" + ownership = b.props.take("OwnershipControls") + if ownership is None: + return None + inner = sub_props(b, ownership, "OwnershipControls") + inner.block("rule", "Rules", self.fill_ownership_rule) + inner.finish() + return b.add_resource( + "aws_s3_bucket_ownership_controls", "_ownership", bucket_items(b) + inner.items + ) + + def fill_ownership_rule(self, r: Props) -> None: + """One ownership rule.""" + r.attr("object_ownership", "ObjectOwnership") + + def access_control(self, b: Builder, ownership_address: str | None) -> None: + """AccessControl (a canned ACL) as aws_s3_bucket_acl, after the ownership controls + at `ownership_address` when there are any.""" + acl = b.props.take("AccessControl") + if acl is None: + return + value = self.canned_acl.get(acl, acl) if isinstance(acl, str) else b.ctx.expr(acl) + items = bucket_items(b) + [Attr("acl", value)] + if ownership_address: + # S3 rejects ACLs until the ownership setting allows them. + items += [BLANK, Attr("depends_on", [Raw(ownership_address)])] + else: + b.ctx.note( + f"{b.logical_id} sets AccessControl: S3 disables ACLs by default, so the " + "aws_s3_bucket_acl only works once OwnershipControls is ObjectWriter or " + "BucketOwnerPreferred" + ) + b.add_resource("aws_s3_bucket_acl", "_acl", items) + + def lifecycle(self, b: Builder) -> None: + """LifecycleConfiguration as aws_s3_bucket_lifecycle_configuration.""" + lifecycle = b.props.take("LifecycleConfiguration") + if lifecycle is None: + return + inner = sub_props(b, lifecycle, "LifecycleConfiguration") + inner.block("rule", "Rules", LifecycleRules().fill) + inner.finish() + b.add_resource( + "aws_s3_bucket_lifecycle_configuration", "_lifecycle", bucket_items(b) + inner.items + ) + + def cors(self, b: Builder) -> None: + """CorsConfiguration as aws_s3_bucket_cors_configuration.""" + cors = b.props.take("CorsConfiguration") + if cors is None: + return + inner = sub_props(b, cors, "CorsConfiguration") + inner.block("cors_rule", "CorsRules", self.fill_cors_rule) + inner.finish() + b.add_resource("aws_s3_bucket_cors_configuration", "_cors", bucket_items(b) + inner.items) + + def fill_cors_rule(self, r: Props) -> None: + """One CORS rule.""" + r.attr("id", "Id") + r.list_attr("allowed_headers", "AllowedHeaders") + r.list_attr("allowed_methods", "AllowedMethods") + r.list_attr("allowed_origins", "AllowedOrigins") + r.list_attr("expose_headers", "ExposedHeaders") + r.number("max_age_seconds", "MaxAge") + + def website(self, b: Builder) -> None: + """WebsiteConfiguration as aws_s3_bucket_website_configuration.""" + website = b.props.take("WebsiteConfiguration") + if website is None: + return + inner = sub_props(b, website, "WebsiteConfiguration") + index = inner.take("IndexDocument") + if index is not None: + inner.items.append(Block("index_document", [], [Attr("suffix", b.ctx.expr(index))])) + error = inner.take("ErrorDocument") + if error is not None: + inner.items.append(Block("error_document", [], [Attr("key", b.ctx.expr(error))])) + inner.block("redirect_all_requests_to", "RedirectAllRequestsTo", self.fill_redirect_all) + inner.block("routing_rule", "RoutingRules", self.fill_routing_rule) + inner.finish() + b.add_resource( + "aws_s3_bucket_website_configuration", "_website", bucket_items(b) + inner.items + ) + + def fill_redirect_all(self, r: Props) -> None: + """Where a website bucket sends every request.""" + r.attrs({"host_name": "HostName", "protocol": "Protocol"}) + + def fill_routing_rule(self, r: Props) -> None: + """One website routing rule.""" + r.block("condition", "RoutingRuleCondition", self.fill_routing_condition) + r.block("redirect", "RedirectRule", self.fill_routing_redirect) + + def fill_routing_condition(self, c: Props) -> None: + """When a routing rule applies.""" + c.attrs( + { + "http_error_code_returned_equals": "HttpErrorCodeReturnedEquals", + "key_prefix_equals": "KeyPrefixEquals", + } + ) + + def fill_routing_redirect(self, c: Props) -> None: + """Where a routing rule redirects to.""" + c.attrs( + { + "host_name": "HostName", + "http_redirect_code": "HttpRedirectCode", + "protocol": "Protocol", + "replace_key_prefix_with": "ReplaceKeyPrefixWith", + "replace_key_with": "ReplaceKeyWith", + } + ) + + def logging(self, b: Builder) -> None: + """LoggingConfiguration as aws_s3_bucket_logging.""" + logging = b.props.take("LoggingConfiguration") + if logging is None: + return + inner = sub_props(b, logging, "LoggingConfiguration") + if not inner.attr("target_bucket", "DestinationBucketName"): + # Without a destination, S3 writes the logs to the bucket itself. + inner.set("target_bucket", b.self_ref("id")) + if not inner.attr("target_prefix", "LogFilePrefix"): + inner.set("target_prefix", "") + inner.finish() + b.add_resource("aws_s3_bucket_logging", "_logging", bucket_items(b) + inner.items) + + def accelerate(self, b: Builder) -> None: + """AccelerateConfiguration as aws_s3_bucket_accelerate_configuration.""" + accelerate = b.props.take("AccelerateConfiguration") + if accelerate is None: + return + inner = sub_props(b, accelerate, "AccelerateConfiguration") + inner.attr("status", "AccelerationStatus") + inner.finish() + b.add_resource( + "aws_s3_bucket_accelerate_configuration", "_accelerate", bucket_items(b) + inner.items + ) + + def object_lock(self, b: Builder) -> None: + """ObjectLockConfiguration as aws_s3_bucket_object_lock_configuration.""" + lock = b.props.take("ObjectLockConfiguration") + if lock is None: + return + inner = sub_props(b, lock, "ObjectLockConfiguration") + inner.drop("ObjectLockEnabled") + inner.block("rule", "Rule", self.fill_object_lock_rule) + inner.finish() + b.add_resource( + "aws_s3_bucket_object_lock_configuration", + "_object_lock", + bucket_items(b) + inner.items, + ) + + def fill_object_lock_rule(self, r: Props) -> None: + """The object lock rule.""" + r.block("default_retention", "DefaultRetention", self.fill_default_retention) + + def fill_default_retention(self, d: Props) -> None: + """The default retention of the object lock rule.""" + d.attr("mode", "Mode") + d.number("days", "Days") + d.number("years", "Years") + + def notification(self, b: Builder) -> None: + """NotificationConfiguration as aws_s3_bucket_notification.""" + notification = b.props.take("NotificationConfiguration") + if notification is None: + return + inner = sub_props(b, notification, "NotificationConfiguration") + for tf_name, cfn_name, target_attr, target_key in self.notification_targets: + inner.block(tf_name, cfn_name, NotificationTarget(target_attr, target_key).fill) + when, bridge = b.ctx.optional_item(inner.take("EventBridgeConfiguration")) + bridge = inner.literal("EventBridgeConfiguration", dict, value=bridge) + if bridge is not None: + enabled = b.ctx.expr(literal_bool(bridge.get("EventBridgeEnabled", True))) + if when is not None: + enabled = Raw(f"{when} ? {wrap_operand(hcl.inline(enabled))} : false") + inner.set("eventbridge", enabled) + inner.finish() + b.add_resource("aws_s3_bucket_notification", "_notification", bucket_items(b) + inner.items) + + +class S3BucketPolicy(ResourceConverter): + """AWS::S3::BucketPolicy as aws_s3_bucket_policy.""" + + cfn_type = "AWS::S3::BucketPolicy" + tf_type = "aws_s3_bucket_policy" + + def convert(self, b: Builder) -> None: + """The bucket and its policy document.""" + b.props.attr("bucket", "Bucket") + b.props.json("policy", "PolicyDocument") + + +# --- DynamoDB --------------------------------------------------------------------------- + + +class TableEncryption: + """Fills the server_side_encryption block of one table, which may look up its KMS key.""" + + def __init__(self, b: Builder) -> None: + """The encryption of the table `b` builds.""" + self.b = b + + def fill(self, s: Props) -> None: + """The server_side_encryption block.""" + s.boolean("enabled", "SSEEnabled") + s.attr("kms_key_arn", "KMSMasterKeyId", self.kms_key_arn) + s.drop("SSEType") + + def kms_key_arn(self, value: Any) -> Any: + """KMSMasterKeyId takes a key ID, ARN, alias name or alias ARN (and Ref of a KMS key + gives its ID); kms_key_arn in Terraform takes only an ARN.""" + b = self.b + if isinstance(value, str) and value.startswith("arn:"): + return value + if isinstance(value, dict) and intrinsic_name(value) == "Fn::GetAtt": + return b.ctx.expr(value) + if isinstance(value, dict) and set(value) == {"Ref"}: + info = b.ctx.resources.get(str(value["Ref"])) + if info is not None and info.cfn_type == "AWS::KMS::Key" and info.kind == "aws": + return Raw(info.expression("arn")) + key = b.add_data("aws_kms_key", "_sse_key", [Attr("key_id", b.ctx.expr(value))]) + return Raw(f"{key}.arn") + + +class DynamoDbTable(ResourceConverter): + """AWS::DynamoDB::Table as aws_dynamodb_table.""" + + cfn_type = "AWS::DynamoDB::Table" + tf_type = "aws_dynamodb_table" + ref = "name" + attrs = {"Arn": "arn", "StreamArn": "stream_arn"} + import_id = "TableName" + + def convert(self, b: Builder) -> None: + """The table, its keys, attributes, indexes and settings.""" + p = b.props + b.name_attr("name", "TableName") + p.attr("billing_mode", "BillingMode") + hash_key, range_key = self.key_names(p) + if hash_key is not None: + p.set("hash_key", b.ctx.expr(hash_key)) + if range_key is not None: + p.set("range_key", b.ctx.expr(range_key)) + self.throughput(p) + p.attr("table_class", "TableClass") + p.boolean("deletion_protection_enabled", "DeletionProtectionEnabled") + self.stream(b) + self.attribute_definitions(b) + p.block("global_secondary_index", "GlobalSecondaryIndexes", self.fill_global_index) + p.block("local_secondary_index", "LocalSecondaryIndexes", self.fill_local_index) + p.block("ttl", "TimeToLiveSpecification", self.fill_ttl) + p.block("server_side_encryption", "SSESpecification", TableEncryption(b).fill) + p.block( + "point_in_time_recovery", + "PointInTimeRecoverySpecification", + self.fill_point_in_time_recovery, + ) + p.block("on_demand_throughput", "OnDemandThroughput", fill_on_demand_throughput) + p.tags() + + def stream(self, b: Builder) -> None: + """StreamSpecification as stream_enabled and stream_view_type.""" + p = b.props + when, stream = optional_structure(p, "StreamSpecification", p.take("StreamSpecification")) + if stream is None: + return + inner = sub_props(b, stream, "StreamSpecification") + view = b.ctx.expr(inner.take("StreamViewType")) + if when is None: + p.set("stream_enabled", True) + p.set("stream_view_type", view) + else: + p.set("stream_enabled", Raw(when)) + p.set("stream_view_type", Raw(f"{when} ? {wrap_operand(hcl.inline(view))} : null")) + # ResourcePolicy and Tags (for the stream) have no counterpart on the table. + inner.finish() + p.items.extend(inner.items) + + def attribute_definitions(self, b: Builder) -> None: + """One attribute block per attribute definition.""" + p = b.props + for item in p.literal("AttributeDefinitions", list) or []: + when, attribute = optional_structure(p, "AttributeDefinitions", item) + if attribute is None: + continue + p.items.append( + optional_block( + "attribute", + [ + Attr("name", b.ctx.expr(attribute.get("AttributeName"))), + Attr("type", b.ctx.expr(attribute.get("AttributeType"))), + ], + when, + ) + ) + + def key_schema(self, r: Props) -> list[dict[str, Any]]: + """KeySchema entries that are literal mappings (the others are noted).""" + keys = [ + r.literal("KeySchema", dict, value=key) for key in r.literal("KeySchema", list) or [] + ] + return [key for key in keys if key is not None] + + def key_names(self, r: Props) -> tuple[Any, Any]: + """The hash and range key attribute names (None when absent).""" + hash_key = range_key = None + for key in self.key_schema(r): + if key.get("KeyType") == "HASH": + hash_key = key.get("AttributeName") + elif key.get("KeyType") == "RANGE": + range_key = key.get("AttributeName") + return hash_key, range_key + + def throughput(self, r: Props) -> None: + """ProvisionedThroughput as read_capacity and write_capacity.""" + throughput = r.literal("ProvisionedThroughput", dict) + if throughput is not None: + r.set("read_capacity", r.ctx.expr(throughput.get("ReadCapacityUnits"))) + r.set("write_capacity", r.ctx.expr(throughput.get("WriteCapacityUnits"))) + + def projection(self, r: Props) -> None: + """The Projection of an index as projection_type and non_key_attributes.""" + projection = r.literal("Projection", dict) + if projection is None: + return + if projection.get("ProjectionType"): + r.set("projection_type", r.ctx.expr(projection["ProjectionType"])) + else: + r.set("projection_type", "ALL") + if projection.get("NonKeyAttributes"): + r.set("non_key_attributes", r.ctx.expr(projection["NonKeyAttributes"])) + + def fill_global_index(self, r: Props) -> None: + """One global secondary index.""" + r.attr("name", "IndexName") + for key in self.key_schema(r): + r.items.append( + Block( + "key_schema", + [], + [ + Attr("attribute_name", r.ctx.expr(key.get("AttributeName"))), + Attr("key_type", r.ctx.expr(key.get("KeyType"))), + ], + ) + ) + self.projection(r) + self.throughput(r) + r.block("on_demand_throughput", "OnDemandThroughput", fill_on_demand_throughput) + + def fill_local_index(self, r: Props) -> None: + """One local secondary index.""" + r.attr("name", "IndexName") + _, range_key = self.key_names(r) + if range_key is not None: + r.set("range_key", r.ctx.expr(range_key)) + self.projection(r) + + def fill_ttl(self, t: Props) -> None: + """The ttl block.""" + t.attr("attribute_name", "AttributeName") + t.boolean("enabled", "Enabled") + + def fill_point_in_time_recovery(self, s: Props) -> None: + """The point_in_time_recovery block.""" + s.boolean("enabled", "PointInTimeRecoveryEnabled") + s.number("recovery_period_in_days", "RecoveryPeriodInDays") + + +# --- ECR -------------------------------------------------------------------------------- + + +class EcrRepository(ResourceConverter): + """AWS::ECR::Repository as aws_ecr_repository, with its lifecycle and repository + policies as separate resources.""" + + cfn_type = "AWS::ECR::Repository" + tf_type = "aws_ecr_repository" + ref = "name" + attrs = {"Arn": "arn", "RepositoryUri": "repository_url"} + import_id = "RepositoryName" + + def convert(self, b: Builder) -> None: + """The repository, then its policies.""" + p = b.props + b.name_attr("name", "RepositoryName", lowercase=True) + p.attr("image_tag_mutability", "ImageTagMutability") + p.boolean("force_delete", "EmptyOnDelete") + p.block("image_scanning_configuration", "ImageScanningConfiguration", self.fill_scanning) + p.block("encryption_configuration", "EncryptionConfiguration", self.fill_encryption) + p.tags() + self.lifecycle_policy(b) + policy = p.take("RepositoryPolicyText") + if policy is not None: + b.add_resource( + "aws_ecr_repository_policy", + "_policy", + [Attr("repository", b.self_ref("name")), Attr("policy", b.ctx.json(policy))], + ) + + def fill_scanning(self, s: Props) -> None: + """The image_scanning_configuration block.""" + s.boolean("scan_on_push", "ScanOnPush") + + def fill_encryption(self, e: Props) -> None: + """The encryption_configuration block.""" + e.attrs({"encryption_type": "EncryptionType", "kms_key": "KmsKey"}) + + def lifecycle_policy(self, b: Builder) -> None: + """LifecyclePolicy as aws_ecr_lifecycle_policy.""" + p = b.props + when, lifecycle = optional_structure(p, "LifecyclePolicy", p.take("LifecyclePolicy")) + if lifecycle is None: + return + inner = sub_props(b, lifecycle, "LifecyclePolicy") + text = inner.take("LifecyclePolicyText") + # RegistryId (the registry of another account) has no counterpart: it is reported. + inner.finish() + if text is None: + p.items.extend(inner.items) + return + b.add_resource( + "aws_ecr_lifecycle_policy", + "_lifecycle", + [Attr("repository", b.self_ref("name")), Attr("policy", b.ctx.json(text))] + + inner.items, + when=when, + ) + + +CONVERTERS: tuple[type[ResourceConverter], ...] = ( + S3Bucket, + S3BucketPolicy, + DynamoDbTable, + EcrRepository, +) diff --git a/services/converter-api/converters/cfn/sam.py b/services/converter-api/converters/cfn/sam.py new file mode 100644 index 0000000..258526f --- /dev/null +++ b/services/converter-api/converters/cfn/sam.py @@ -0,0 +1,1278 @@ +"""AWS SAM templates expanded into plain CloudFormation, the way the SAM transform does it. + +Each AWS::Serverless::* resource becomes the resources SAM itself would create, with the +logical IDs SAM uses (MyFunctionRole, ServerlessRestApi, MyFunctionMyEventPermission...), so +`!GetAtt MyFunctionRole.Arn` and `!Ref ServerlessRestApi` in the template keep working. +Local code paths (CodeUri: ./src) are passed to the Lambda converter as hints, so it can zip +them with an archive_file data source. + +The work is split by concern: `Expansion` holds the state of one run, `IamWriter` writes +roles and Lambda permissions, `RuleWriter` writes EventBridge rules and schedules, and one +expander class per kind of serverless resource builds on those. `SamExpander` runs them in +the order SAM does. +""" + +from __future__ import annotations + +import copy +import json +import re +from collections.abc import Callable +from typing import Any + +from converters.cfn.constants import SAM_TRANSFORM +from converters.cfn.errors import CfnError +from converters.cfn.hcl import template_text +from converters.cfn.models import Expression +from converters.cfn.sam_constants import ( + BASIC_EXECUTION, + CONNECTOR_ACTIONS, + FUNCTION_PROPERTIES, + GLOBAL_SECTIONS, + INHERITED, + PARTITION_ARN, + POLLER_PROPERTIES, + POLLERS, + PRINCIPALS, + REF_IS_ARN, + ROLE_PROPERTY, + S3_URI, + SERVERLESS_TYPES, + SUB_REFERENCE, +) +from converters.cfn.sam_policies import ( + PolicyTemplates, + document, + inline_policy, + managed_policy, + statement, + sub, +) + +# --- value helpers ---------------------------------------------------------------------- + + +def is_function(value: dict[str, Any]) -> bool: + """Whether a mapping is an intrinsic function call (Ref, Fn::*).""" + return len(value) == 1 and str(next(iter(value))).startswith(("Fn::", "Ref")) + + +def merge_globals(global_props: dict[str, Any], props: dict[str, Any]) -> dict[str, Any]: + """The Globals rules of SAM: the value of the resource wins, maps merge, lists add up.""" + merged = copy.deepcopy(global_props) + for name, value in props.items(): + current = merged.get(name) + if ( + isinstance(current, dict) + and isinstance(value, dict) + and not is_function(current) + and not is_function(value) + ): + merged[name] = merge_globals(current, value) + elif isinstance(current, list) and isinstance(value, list): + merged[name] = current + value + else: + merged[name] = value + return merged + + +def tag_list(tags: Any) -> Any: + """SAM writes tags as a map; most CloudFormation types take [{Key, Value}].""" + if isinstance(tags, dict) and not is_function(tags): + return [{"Key": k, "Value": v} for k, v in tags.items()] + return tags + + +def local_path(value: str) -> str: + """A local code path without the leading ./ and the trailing slash.""" + return value.strip().removeprefix("./").rstrip("/") or "." + + +def file_body(uri: str) -> Expression: + """A definition file next to the Terraform files, read with yamldecode (which reads + JSON as well, so this works for either kind of definition file).""" + path = template_text(local_path(uri)) + return Expression(f'yamldecode(file("${{path.module}}/{path}"))') + + +def s3_location(uri: Any) -> Any: + """An s3://bucket/key URI as {Bucket, Key}; any other value as it is.""" + match = S3_URI.match(uri) if isinstance(uri, str) else None + if match: + return {"Bucket": match.group(1), "Key": match.group(2)} + return uri + + +def alnum(text: str) -> str: + """`text` with only its letters and digits.""" + return re.sub(r"[^A-Za-z0-9]", "", text) + + +def as_list(value: Any) -> list[Any]: + """None as [], a list as it is and any other value as a list of one.""" + if value is None: + return [] + return value if isinstance(value, list) else [value] + + +def unique(values: list[Any]) -> list[Any]: + """Values without repeats, in order. Keys are JSON text, so it stays linear.""" + seen: set[str] = set() + out: list[Any] = [] + for value in values: + key = json.dumps(value, sort_keys=True, default=str) + if key not in seen: + seen.add(key) + out.append(value) + return out + + +def ref_id(value: Any) -> str | None: + """The logical id in {Id: X}, {Ref: X} or a plain X.""" + if isinstance(value, dict): + for key in ("Id", "Ref"): + if isinstance(value.get(key), str): + return value[key] + return value if isinstance(value, str) else None + + +def meta(resource: dict[str, Any]) -> dict[str, Any]: + """The DependsOn and Metadata attributes of a resource.""" + return {k: resource[k] for k in ("DependsOn", "Metadata") if k in resource} + + +def substitute(definition: Any, substitutions: dict[str, Any]) -> Any: + """SAM DefinitionSubstitutions applied to a definition object: `${Name}` in a string + becomes the value, through Fn::Sub when the value is computed.""" + if isinstance(definition, dict): + return {k: substitute(v, substitutions) for k, v in definition.items()} + if isinstance(definition, list): + return [substitute(v, substitutions) for v in definition] + if isinstance(definition, str) and "${" in definition: + used = {k: v for k, v in substitutions.items() if "${" + k + "}" in definition} + if not used: + return definition + if all(isinstance(v, str | int | float) for v in used.values()): + for name, value in used.items(): + definition = definition.replace("${" + name + "}", str(value)) + return definition + return {"Fn::Sub": [definition, used]} + return definition + + +class ReferenceRewriter: + """Points `!Ref MyFunction.Alias`, `!Ref MyApi.Stage` and the like (in Ref and Fn::Sub) + at the generated resources they stand for.""" + + def __init__(self, aliases: dict[str, str]) -> None: + """`aliases`: "MyApi.Stage" -> the logical id of the generated stage.""" + self.aliases = aliases + + def replace(self, match: re.Match[str]) -> str: + """One `${MyApi.Stage}` of a Fn::Sub string, rewritten when it is an alias.""" + name = match.group(1) + if name in self.aliases: + return "${" + self.aliases[name] + "}" + return match.group(0) + + def rewrite_sub(self, text: str) -> str: + """`${MyApi.Stage}` in a Fn::Sub string means the stage resource, as with Ref.""" + return SUB_REFERENCE.sub(self.replace, text) + + def rewrite(self, value: Any) -> Any: + """`value` with every alias reference rewritten.""" + if isinstance(value, dict): + if set(value) == {"Ref"} and value["Ref"] in self.aliases: + return {"Ref": self.aliases[value["Ref"]]} + if set(value) == {"Fn::Sub"}: + args = value["Fn::Sub"] + if isinstance(args, str): + return {"Fn::Sub": self.rewrite_sub(args)} + if isinstance(args, list) and args and isinstance(args[0], str): + rest = [self.rewrite(item) for item in args[1:]] + return {"Fn::Sub": [self.rewrite_sub(args[0])] + rest} + return {k: self.rewrite(v) for k, v in value.items()} + if isinstance(value, list): + return [self.rewrite(v) for v in value] + return value + + +# --- shared state and writers ----------------------------------------------------------- + + +class Expansion: + """The state of one SAM expansion: the source resources, the generated ones, notes, + converter hints, the generated API paths and the aliases of generated resources.""" + + def __init__(self, template: dict[str, Any], notes: list[str]) -> None: + """Start from `template` (a copy the expansion may change) and the notes list.""" + self.template = template + self.notes = notes + self.source: dict[str, dict[str, Any]] = template["Resources"] + self.out: dict[str, dict[str, Any]] = {} + self.hints: dict[str, dict[str, Any]] = {} + # API id -> {path: {method: operation}}, for the APIs whose body SAM writes. + self.rest_paths: dict[str, dict[str, Any]] = {} + self.http_paths: dict[str, dict[str, Any]] = {} + self.aliases: dict[str, str] = {} + self.globals = template.get("Globals") or {} + if not isinstance(self.globals, dict): + raise CfnError("Invalid SAM template: 'Globals' must be a mapping") + + def note(self, message: str) -> None: + """Add a note once.""" + if message not in self.notes: + self.notes.append(message) + + def leftovers(self, logical_id: str, props: dict[str, Any]) -> None: + """A note for each SAM property nothing used.""" + for name in props: + self.note(f"{logical_id}: SAM property '{name}' was not converted") + + def add( + self, + logical_id: str, + kind: str, + props: dict[str, Any], + origin: dict[str, Any], + extra: dict[str, Any] | None = None, + ) -> None: + """Add a generated resource. It inherits the Condition and deletion policies of + `origin` (the SAM resource); `extra` holds more resource attributes.""" + resource: dict[str, Any] = {"Type": kind, "Properties": props} + for attribute in INHERITED: + if attribute in origin: + resource[attribute] = origin[attribute] + resource.update(extra or {}) + self.out[logical_id] = resource + + def props(self, resource: dict[str, Any]) -> dict[str, Any]: + """The properties of a SAM resource with its Globals section merged in.""" + kind = resource["Type"] + props = dict(resource.get("Properties") or {}) + for section, section_kind in GLOBAL_SECTIONS.items(): + if kind == section_kind and isinstance(self.globals.get(section), dict): + return merge_globals(self.globals[section], props) + return props + + +class IamWriter: + """The IAM roles and Lambda permissions SAM creates for functions, state machines, + event sources and connectors.""" + + def __init__(self, expansion: Expansion) -> None: + """Write into `expansion`.""" + self.exp = expansion + self.templates = PolicyTemplates() + + def policy_template( + self, owner: str, role_id: str, name: str, params: Any + ) -> list[dict[str, Any]]: + """The statements of one SAM policy template, or a note when it is unknown.""" + template = self.templates.get(name) + if template is None: + self.exp.note( + f"{owner}: SAM policy template '{name}' was not converted; add its " + f"permissions to {role_id} by hand" + ) + return [] + return template(params if isinstance(params, dict) else {}) + + def role( + self, + role_id: str, + service: str, + managed: list[Any], + policies: Any, + inline: list[dict[str, Any]], + origin: dict[str, Any], + extra: dict[str, Any] | None = None, + ) -> None: + """The role SAM creates for a function, state machine or event source. `policies` + is the Policies property of SAM: managed policy names, documents or policy + templates.""" + owner = role_id.removesuffix("Role") + statements: list[dict[str, Any]] = [] + for index, policy in enumerate(as_list(policies)): + if isinstance(policy, str): + managed.append(managed_policy(policy)) + elif isinstance(policy, dict) and "Statement" in policy: + inline.append( + inline_policy(f"{role_id}Policy{index}", as_list(policy["Statement"])) + ) + elif isinstance(policy, dict) and is_function(policy): + managed.append(policy) + elif isinstance(policy, dict) and len(policy) == 1: + ((name, params),) = policy.items() + statements.extend(self.policy_template(owner, role_id, name, params)) + else: + self.exp.note(f"{owner}: a Policies entry was not converted; add it to {role_id}") + if statements: + inline.append(inline_policy(f"{role_id}PolicyTemplates", statements)) + role: dict[str, Any] = { + "AssumeRolePolicyDocument": document( + [ + { + "Effect": "Allow", + "Principal": {"Service": [service]}, + "Action": ["sts:AssumeRole"], + } + ] + ) + } + role.update(extra or {}) + if managed: + role["ManagedPolicyArns"] = unique(managed) + if inline: + role["Policies"] = inline + self.exp.add(role_id, "AWS::IAM::Role", role, origin) + + def permission( + self, + logical_id: str, + function: Any, + principal: str, + source_arn: Any, + origin: dict[str, Any], + account: bool = False, + ) -> None: + """A Lambda permission for `principal` to invoke `function`.""" + props: dict[str, Any] = { + "Action": "lambda:InvokeFunction", + "FunctionName": function, + "Principal": principal, + } + if source_arn is not None: + props["SourceArn"] = source_arn + if account: + props["SourceAccount"] = {"Ref": "AWS::AccountId"} + self.exp.add(logical_id, "AWS::Lambda::Permission", props, origin) + + +class RuleWriter: + """The EventBridge rules and EventBridge Scheduler schedules behind the Schedule, + EventBridgeRule and ScheduleV2 events of functions and state machines.""" + + def __init__(self, expansion: Expansion, iam: IamWriter) -> None: + """Write into `expansion`, with roles from `iam`.""" + self.exp = expansion + self.iam = iam + + def rule( + self, + event_id: str, + kind: str, + props: dict[str, Any], + target: dict[str, Any], + origin: dict[str, Any], + ) -> None: + """An AWS::Events::Rule for a Schedule, CloudWatchEvent or EventBridgeRule event.""" + rule: dict[str, Any] = {} + if kind == "Schedule": + rule["ScheduleExpression"] = props.get("Schedule") + else: + rule["EventPattern"] = props.get("Pattern") + if "EventBusName" in props: + rule["EventBusName"] = props["EventBusName"] + for source in ("Name", "RuleName"): + if source in props: + rule["Name"] = props[source] + for name in ("Description", "State"): + if name in props: + rule[name] = props[name] + if "Enabled" in props and "State" not in rule: + rule["State"] = "ENABLED" if str(props["Enabled"]).lower() == "true" else "DISABLED" + for name in ("Input", "InputPath"): + if name in props: + target[name] = props[name] + rule["Targets"] = [target] + self.exp.add(event_id, "AWS::Events::Rule", rule, origin) + + def schedule_v2( + self, event_id: str, props: dict[str, Any], target: Any, action: str, origin: dict[str, Any] + ) -> None: + """An AWS::Scheduler::Schedule and the role it runs `action` on `target` with.""" + role_id = f"{event_id}Role" + schedule: dict[str, Any] = { + "ScheduleExpression": props.get("ScheduleExpression"), + "FlexibleTimeWindow": props.get("FlexibleTimeWindow") or {"Mode": "OFF"}, + "Target": {"Arn": target, "RoleArn": {"Fn::GetAtt": [role_id, "Arn"]}}, + } + for name in ( + "Name", + "Description", + "State", + "ScheduleExpressionTimezone", + "GroupName", + "StartDate", + "EndDate", + ): + if name in props: + schedule[name] = props[name] + if "Input" in props: + schedule["Target"]["Input"] = props["Input"] + self.exp.add(event_id, "AWS::Scheduler::Schedule", schedule, origin) + self.iam.role( + role_id, + "scheduler.amazonaws.com", + [], + None, + [inline_policy(f"{event_id}Policy", [statement([action], target)])], + origin, + ) + + +# --- functions -------------------------------------------------------------------------- + + +class FunctionExpander: + """AWS::Serverless::Function: the function, its role, alias, URL and event sources.""" + + def __init__(self, expansion: Expansion, iam: IamWriter, rules: RuleWriter) -> None: + """Write into `expansion` with the shared writers.""" + self.exp = expansion + self.iam = iam + self.rules = rules + + def expand(self, logical_id: str, resource: dict[str, Any]) -> None: + """Expand one function.""" + p = self.exp.props(resource) + managed: list[Any] = [managed_policy(BASIC_EXECUTION)] + inline: list[dict[str, Any]] = [] + fn: dict[str, Any] = {name: p.pop(name) for name in FUNCTION_PROPERTIES if name in p} + if "VpcConfig" in fn: + # SAM gives functions in a VPC the permissions to manage their network interfaces. + managed.append(managed_policy("service-role/AWSLambdaVPCAccessExecutionRole")) + self.code(logical_id, p, fn) + + tracing = p.pop("Tracing", None) + if tracing is not None: + fn["TracingConfig"] = {"Mode": tracing} + if tracing == "Active": + managed.append(managed_policy("AWSXrayWriteOnlyAccess")) + dlq = p.pop("DeadLetterQueue", None) + if isinstance(dlq, dict): + fn["DeadLetterConfig"] = {"TargetArn": dlq.get("TargetArn")} + action = "sns:Publish" if dlq.get("Type") == "SNS" else "sqs:SendMessage" + inline.append( + inline_policy( + f"{logical_id}RoleDeadLetterQueuePolicy", + [statement([action], dlq.get("TargetArn"))], + ) + ) + if "Tags" in p: + fn["Tags"] = tag_list(p.pop("Tags")) + + role = p.pop("Role", None) + policies = p.pop("Policies", None) + role_extra = { + name: p.pop(source) + for source, name in ( + ("PermissionsBoundary", "PermissionsBoundary"), + ("RolePath", "Path"), + ) + if source in p + } + assume = p.pop("AssumeRolePolicyDocument", None) + events = p.pop("Events", None) or {} + alias = p.pop("AutoPublishAlias", None) + url = p.pop("FunctionUrlConfig", None) + + if role is None: + fn["Role"] = {"Fn::GetAtt": [f"{logical_id}Role", "Arn"]} + else: + fn["Role"] = role + if policies: + self.exp.note( + f"{logical_id} sets both Role and Policies: SAM ignores Policies then, so " + "they were not converted" + ) + self.exp.add(logical_id, "AWS::Lambda::Function", fn, resource, meta(resource)) + + target: Any = {"Fn::GetAtt": [logical_id, "Arn"]} + if alias is not None: + target = self.alias(logical_id, alias, resource) + if not isinstance(events, dict): + raise CfnError(f"Invalid SAM template: 'Events' of '{logical_id}' must be a mapping") + for event_name, event in events.items(): + if not isinstance(event, dict): + raise CfnError( + f"Invalid SAM template: event '{event_name}' of '{logical_id}' must be a " + "mapping" + ) + managed.extend(self.event(f"{logical_id}{event_name}", event, target, resource)) + if isinstance(url, dict): + self.url( + logical_id, url, target if alias is not None else {"Ref": logical_id}, resource + ) + + if role is None: + if assume is not None: + role_extra["AssumeRolePolicyDocument"] = assume + self.iam.role( + f"{logical_id}Role", + "lambda.amazonaws.com", + managed, + policies, + inline, + resource, + role_extra, + ) + for name in ("DeploymentPreference", "ProvisionedConcurrencyConfig", "EventInvokeConfig"): + if p.pop(name, None) is not None: + self.exp.note( + f"{logical_id}: the SAM setting {name} was not converted; set it up by hand" + ) + p.pop("Metadata", None) + self.exp.leftovers(logical_id, p) + + def code(self, logical_id: str, p: dict[str, Any], fn: dict[str, Any]) -> None: + """The Code of the function, or a code_path hint for a local folder.""" + image = p.pop("ImageUri", None) + inline = p.pop("InlineCode", None) + code = p.pop("CodeUri", None) + match = S3_URI.match(code) if isinstance(code, str) else None + if image is not None: + fn["Code"] = {"ImageUri": image} + fn["PackageType"] = "Image" + elif inline is not None: + fn["Code"] = {"ZipFile": inline} + elif isinstance(code, dict) and "Bucket" in code: + fn["Code"] = {"S3Bucket": code["Bucket"], "S3Key": code.get("Key")} + if "Version" in code: + fn["Code"]["S3ObjectVersion"] = code["Version"] + elif match: + fn["Code"] = {"S3Bucket": match.group(1), "S3Key": match.group(2)} + elif isinstance(code, str): + self.exp.hints.setdefault(logical_id, {})["code_path"] = local_path(code) + elif code is not None: + self.exp.note(f"{logical_id}: CodeUri is computed by a function and was not converted") + + def alias(self, logical_id: str, alias: Any, origin: dict[str, Any]) -> dict[str, Any]: + """The version and alias of AutoPublishAlias. Returns a Ref to the alias.""" + version_id = f"{logical_id}Version" + alias_id = f"{logical_id}Alias{alnum(alias) if isinstance(alias, str) else ''}" + self.exp.add( + version_id, "AWS::Lambda::Version", {"FunctionName": {"Ref": logical_id}}, origin + ) + self.exp.add( + alias_id, + "AWS::Lambda::Alias", + { + "FunctionName": {"Ref": logical_id}, + "FunctionVersion": {"Fn::GetAtt": [version_id, "Version"]}, + "Name": alias, + }, + origin, + ) + self.exp.aliases[f"{logical_id}.Alias"] = alias_id + self.exp.aliases[f"{logical_id}.Version"] = version_id + return {"Ref": alias_id} + + def url( + self, logical_id: str, url: dict[str, Any], target: Any, origin: dict[str, Any] + ) -> None: + """FunctionUrlConfig: the function URL, and a public permission for AuthType NONE.""" + props: dict[str, Any] = { + "TargetFunctionArn": target, + "AuthType": url.get("AuthType", "AWS_IAM"), + } + for name in ("Cors", "InvokeMode"): + if name in url: + props[name] = url[name] + self.exp.add(f"{logical_id}Url", "AWS::Lambda::Url", props, origin) + if props["AuthType"] == "NONE": + self.exp.add( + f"{logical_id}UrlPublicPermissions", + "AWS::Lambda::Permission", + { + "Action": "lambda:InvokeFunctionUrl", + "FunctionName": target, + "Principal": "*", + "FunctionUrlAuthType": "NONE", + }, + origin, + ) + + def event( + self, event_id: str, event: dict[str, Any], target: Any, origin: dict[str, Any] + ) -> list[Any]: + """One entry of the Events of a function. Returns managed policies the role needs.""" + kind = event.get("Type") + props = event.get("Properties") or {} + if kind in POLLERS: + return self.poller(event_id, kind, props, target, origin) + if kind in ("Schedule", "CloudWatchEvent", "EventBridgeRule"): + self.rules.rule( + event_id, kind, props, {"Arn": target, "Id": f"{event_id}LambdaTarget"}, origin + ) + self.iam.permission( + f"{event_id}Permission", + target, + "events.amazonaws.com", + {"Fn::GetAtt": [event_id, "Arn"]}, + origin, + ) + elif kind == "ScheduleV2": + self.rules.schedule_v2(event_id, props, target, "lambda:InvokeFunction", origin) + elif kind == "SNS": + self.sns_event(event_id, props, target, origin) + elif kind == "S3": + self.s3_event(event_id, props, target, origin) + elif kind == "CloudWatchLogs": + self.iam.permission(f"{event_id}Permission", target, "logs.amazonaws.com", None, origin) + self.exp.add( + event_id, + "AWS::Logs::SubscriptionFilter", + { + "DestinationArn": target, + "FilterPattern": props.get("FilterPattern", ""), + "LogGroupName": props.get("LogGroupName"), + }, + origin, + {"DependsOn": [f"{event_id}Permission"]}, + ) + elif kind == "Api": + self.api_event(event_id, props, target, origin, http=False) + elif kind == "HttpApi": + self.api_event(event_id, props, target, origin, http=True) + else: + self.exp.note( + f"{event_id}: SAM event type '{kind}' was not converted; connect the event " + "source by hand" + ) + return [] + + def poller( + self, + event_id: str, + kind: str, + props: dict[str, Any], + target: Any, + origin: dict[str, Any], + ) -> list[Any]: + """An SQS, Kinesis or DynamoDB event: an event source mapping. Returns the managed + policy SAM attaches for it.""" + source_key, policy = POLLERS[kind] + mapping: dict[str, Any] = { + "EventSourceArn": props.get(source_key), + "FunctionName": target, + } + mapping.update({k: props[k] for k in POLLER_PROPERTIES if k in props}) + self.exp.add(event_id, "AWS::Lambda::EventSourceMapping", mapping, origin) + return [managed_policy(policy)] + + def sns_event( + self, event_id: str, props: dict[str, Any], target: Any, origin: dict[str, Any] + ) -> None: + """An SNS event: a subscription of the function and the permission it needs.""" + subscription: dict[str, Any] = { + "Protocol": "lambda", + "Endpoint": target, + "TopicArn": props.get("Topic"), + } + for name in ("FilterPolicy", "FilterPolicyScope", "Region", "RedrivePolicy"): + if name in props: + subscription[name] = props[name] + if props.get("SqsSubscription"): + self.exp.note( + f"{event_id}: the SqsSubscription of the SNS event (a queue between the topic " + "and the function) was not converted" + ) + self.exp.add(event_id, "AWS::SNS::Subscription", subscription, origin) + self.iam.permission( + f"{event_id}Permission", target, "sns.amazonaws.com", props.get("Topic"), origin + ) + + def s3_event( + self, event_id: str, props: dict[str, Any], target: Any, origin: dict[str, Any] + ) -> None: + """S3 notifications live on the bucket, so the bucket in this template gets them.""" + self.iam.permission( + f"{event_id}Permission", target, "s3.amazonaws.com", None, origin, account=True + ) + bucket_id = ref_id(props.get("Bucket")) if isinstance(props.get("Bucket"), dict) else None + bucket = self.exp.source.get(bucket_id or "") + if bucket is None or bucket.get("Type") != "AWS::S3::Bucket": + self.exp.note( + f"{event_id}: the bucket of the S3 event is outside this template; add the " + "notification to that bucket by hand" + ) + return + config: dict[str, Any] = {"Function": target} + if "Filter" in props: + config["Filter"] = props["Filter"] + notification = bucket.setdefault("Properties", {}).setdefault( + "NotificationConfiguration", {} + ) + configs = notification.setdefault("LambdaConfigurations", []) + configs.extend(dict(config, Event=name) for name in as_list(props.get("Events"))) + bucket["DependsOn"] = as_list(bucket.get("DependsOn")) + [f"{event_id}Permission"] + + def api_event( + self, event_id: str, props: dict[str, Any], target: Any, origin: dict[str, Any], http: bool + ) -> None: + """An Api or HttpApi event: an operation in the API body SAM writes, and the + permission for API Gateway to call the function.""" + default_api = "ServerlessHttpApi" if http else "ServerlessRestApi" + api_id = ref_id(props.get("ApiId" if http else "RestApiId")) or default_api + paths = self.exp.http_paths if http else self.exp.rest_paths + path = str(props.get("Path", "$default" if http else "/")) + method = str(props.get("Method", "any")).lower() + if api_id == default_api or api_id in paths: + integration: dict[str, Any] = {"type": "aws_proxy", "httpMethod": "POST"} + if http: + integration["uri"] = target + integration["payloadFormatVersion"] = str(props.get("PayloadFormatVersion", "2.0")) + if "TimeoutInMillis" in props: + integration["timeoutInMillis"] = props["TimeoutInMillis"] + else: + integration["uri"] = sub( + f"{PARTITION_ARN}:apigateway:${{AWS::Region}}:lambda:path/2015-03-31/" + "functions/${fn}/invocations", + {"fn": target}, + ) + operation = "x-amazon-apigateway-any-method" if method == "any" else method + paths.setdefault(api_id, {}).setdefault(path, {})[operation] = { + "x-amazon-apigateway-integration": integration, + "responses": {}, + } + if props.get("Auth"): + self.exp.note( + f"{event_id}: the Auth setting of the API event was not converted; add the " + "authorizer" + ) + if http and path == "$default": + scope = "*" + else: + source_path = re.sub(r"\{[^}]*\}", "*", path) + scope = f"*/{'*' if method == 'any' else method.upper()}{source_path}" + self.iam.permission( + f"{event_id}Permission", + target, + "apigateway.amazonaws.com", + sub( + f"{PARTITION_ARN}:execute-api:${{AWS::Region}}:${{AWS::AccountId}}:${{api}}/{scope}", + {"api": {"Ref": api_id}}, + ), + origin, + ) + + +# --- APIs ------------------------------------------------------------------------------- + + +class ApiExpander: + """AWS::Serverless::Api and AWS::Serverless::HttpApi, and the implicit APIs SAM creates + for function events: the API, its deployment and its stage.""" + + def __init__(self, expansion: Expansion) -> None: + """Write into `expansion`.""" + self.exp = expansion + + def body(self, p: dict[str, Any], generated: dict[str, Any]) -> dict[str, Any]: + """Body (inline or from a local file) or BodyS3Location; `generated` when the + template gives neither.""" + body = p.pop("DefinitionBody", None) + uri = p.pop("DefinitionUri", None) + if body is not None: + return {"Body": body} + if isinstance(uri, str) and not uri.startswith("s3://"): + return {"Body": file_body(uri)} + if uri is not None: + return {"BodyS3Location": s3_location(uri)} + return {"Body": generated} + + def rest_api(self, logical_id: str, resource: dict[str, Any] | None) -> None: + """AWS::Serverless::Api (or the implicit ServerlessRestApi): RestApi, Deployment, Stage.""" + origin = resource or {} + p = self.exp.props(resource or {"Type": "AWS::Serverless::Api"}) + api: dict[str, Any] = {"Name": p.pop("Name", {"Ref": "AWS::StackName"})} + generated = { + "swagger": "2.0", + "info": {"version": "1.0", "title": api["Name"]}, + "paths": self.exp.rest_paths.get(logical_id, {}), + } + api.update(self.body(p, generated)) + for name in ( + "Description", + "BinaryMediaTypes", + "MinimumCompressionSize", + "DisableExecuteApiEndpoint", + "Mode", + "ApiKeySourceType", + ): + if name in p: + api[name] = p.pop(name) + endpoint = p.pop("EndpointConfiguration", None) + if endpoint is not None: + api["EndpointConfiguration"] = ( + {"Types": [endpoint]} if isinstance(endpoint, str) else endpoint + ) + if "Tags" in p: + api["Tags"] = tag_list(p.pop("Tags")) + self.exp.add(logical_id, "AWS::ApiGateway::RestApi", api, origin, meta(origin)) + + stage_name = p.pop("StageName", "Prod") + deployment_id = f"{logical_id}Deployment" + self.exp.add( + deployment_id, + "AWS::ApiGateway::Deployment", + {"RestApiId": {"Ref": logical_id}, "Description": f"Deployment of {logical_id}"}, + origin, + ) + stage: dict[str, Any] = { + "RestApiId": {"Ref": logical_id}, + "DeploymentId": {"Ref": deployment_id}, + "StageName": stage_name, + } + for name in ( + "Variables", + "TracingEnabled", + "CacheClusterEnabled", + "CacheClusterSize", + "MethodSettings", + "AccessLogSetting", + ): + if name in p: + stage[name] = p.pop(name) + stage_id = f"{logical_id}{alnum(str(stage_name))}Stage" + self.exp.add(stage_id, "AWS::ApiGateway::Stage", stage, origin) + self.exp.aliases[f"{logical_id}.Stage"] = stage_id + self.exp.aliases[f"{logical_id}.Deployment"] = deployment_id + for name in ( + "Auth", + "Cors", + "Domain", + "GatewayResponses", + "Models", + "OpenApiVersion", + "CanarySetting", + "AlwaysDeploy", + "MergeDefinitions", + ): + if p.pop(name, None) is not None: + self.exp.note( + f"{logical_id}: SAM API setting '{name}' was not converted; add it to the " + "API definition by hand" + ) + self.exp.leftovers(logical_id, p) + + def http_api(self, logical_id: str, resource: dict[str, Any] | None) -> None: + """AWS::Serverless::HttpApi (or the implicit ServerlessHttpApi): Api and Stage.""" + origin = resource or {} + p = self.exp.props(resource or {"Type": "AWS::Serverless::HttpApi"}) + api: dict[str, Any] = { + "Name": p.pop("Name", {"Ref": "AWS::StackName"}), + "ProtocolType": "HTTP", + } + generated = { + "openapi": "3.0.1", + "info": {"version": "1.0", "title": api["Name"]}, + "paths": self.exp.http_paths.get(logical_id, {}), + } + api.update(self.body(p, generated)) + cors = p.pop("CorsConfiguration", None) + if isinstance(cors, dict): + api["CorsConfiguration"] = cors + elif cors is not None: + self.exp.note( + f"{logical_id}: CorsConfiguration given as a single value was not converted" + ) + for name in ("Description", "DisableExecuteApiEndpoint", "FailOnWarnings"): + if name in p: + api[name] = p.pop(name) + if "Tags" in p: + api["Tags"] = p.pop("Tags") + self.exp.add(logical_id, "AWS::ApiGatewayV2::Api", api, origin, meta(origin)) + + stage_name = p.pop("StageName", "$default") + stage: dict[str, Any] = { + "ApiId": {"Ref": logical_id}, + "StageName": stage_name, + "AutoDeploy": True, + } + for name in ( + "StageVariables", + "AccessLogSettings", + "DefaultRouteSettings", + "RouteSettings", + ): + if name in p: + stage[name] = p.pop(name) + if stage_name == "$default": + stage_id = f"{logical_id}ApiGatewayDefaultStage" + else: + stage_id = f"{logical_id}{alnum(str(stage_name))}Stage" + self.exp.add(stage_id, "AWS::ApiGatewayV2::Stage", stage, origin) + self.exp.aliases[f"{logical_id}.Stage"] = stage_id + for name in ("Auth", "Domain"): + if p.pop(name, None) is not None: + self.exp.note( + f"{logical_id}: SAM HTTP API setting '{name}' was not converted; set it up " + "by hand" + ) + self.exp.leftovers(logical_id, p) + + +# --- tables, layers and state machines -------------------------------------------------- + + +class StorageExpander: + """AWS::Serverless::SimpleTable and AWS::Serverless::LayerVersion.""" + + def __init__(self, expansion: Expansion) -> None: + """Write into `expansion`.""" + self.exp = expansion + + def simple_table(self, logical_id: str, resource: dict[str, Any]) -> None: + """A SimpleTable as a DynamoDB table with one hash key.""" + p = self.exp.props(resource) + key = p.pop("PrimaryKey", None) or {} + name = key.get("Name", "id") + kind = {"String": "S", "Number": "N", "Binary": "B"}.get( + str(key.get("Type", "String")), "S" + ) + table: dict[str, Any] = { + "AttributeDefinitions": [{"AttributeName": name, "AttributeType": kind}], + "KeySchema": [{"AttributeName": name, "KeyType": "HASH"}], + } + if "ProvisionedThroughput" in p: + table["ProvisionedThroughput"] = p.pop("ProvisionedThroughput") + else: + table["BillingMode"] = "PAY_PER_REQUEST" + for prop in ("TableName", "SSESpecification", "PointInTimeRecoverySpecification"): + if prop in p: + table[prop] = p.pop(prop) + if "Tags" in p: + table["Tags"] = tag_list(p.pop("Tags")) + self.exp.add(logical_id, "AWS::DynamoDB::Table", table, resource, meta(resource)) + self.exp.leftovers(logical_id, p) + + def layer(self, logical_id: str, resource: dict[str, Any]) -> None: + """A LayerVersion, with its content in S3 or a code_path hint for a local folder.""" + p = self.exp.props(resource) + layer: dict[str, Any] = { + name: p.pop(name) + for name in ( + "LayerName", + "Description", + "CompatibleRuntimes", + "CompatibleArchitectures", + "LicenseInfo", + ) + if name in p + } + content = p.pop("ContentUri", None) + match = S3_URI.match(content) if isinstance(content, str) else None + if isinstance(content, dict) and "Bucket" in content: + layer["Content"] = {"S3Bucket": content["Bucket"], "S3Key": content.get("Key")} + if "Version" in content: + layer["Content"]["S3ObjectVersion"] = content["Version"] + elif match: + layer["Content"] = {"S3Bucket": match.group(1), "S3Key": match.group(2)} + elif isinstance(content, str): + self.exp.hints.setdefault(logical_id, {})["code_path"] = local_path(content) + extra = {"DeletionPolicy": "Retain"} if p.pop("RetentionPolicy", None) == "Retain" else {} + self.exp.add(logical_id, "AWS::Lambda::LayerVersion", layer, resource, extra) + self.exp.leftovers(logical_id, p) + + +class StateMachineExpander: + """AWS::Serverless::StateMachine: the state machine, its role and its event sources.""" + + def __init__(self, expansion: Expansion, iam: IamWriter, rules: RuleWriter) -> None: + """Write into `expansion` with the shared writers.""" + self.exp = expansion + self.iam = iam + self.rules = rules + + def expand(self, logical_id: str, resource: dict[str, Any]) -> None: + """Expand one state machine.""" + p = self.exp.props(resource) + machine: dict[str, Any] = {} + definition = p.pop("Definition", None) + uri = p.pop("DefinitionUri", None) + substitutions = p.pop("DefinitionSubstitutions", None) + if definition is not None: + machine["Definition"] = substitute(definition, substitutions or {}) + elif isinstance(uri, str) and not uri.startswith("s3://"): + machine["Definition"] = file_body(uri) + if substitutions: + self.exp.note( + f"{logical_id}: DefinitionSubstitutions for a definition file were not " + "applied; use templatefile() in place of file()" + ) + elif uri is not None: + machine["DefinitionS3Location"] = s3_location(uri) + if substitutions: + machine["DefinitionSubstitutions"] = substitutions + for source, dest in ( + ("Name", "StateMachineName"), + ("Type", "StateMachineType"), + ("Logging", "LoggingConfiguration"), + ("Tracing", "TracingConfiguration"), + ): + if source in p: + machine[dest] = p.pop(source) + if "Tags" in p: + machine["Tags"] = tag_list(p.pop("Tags")) + role = p.pop("Role", None) + policies = p.pop("Policies", None) + extra = ( + {"PermissionsBoundary": p.pop("PermissionsBoundary")} + if "PermissionsBoundary" in p + else {} + ) + machine["RoleArn"] = ( + role if role is not None else {"Fn::GetAtt": [f"{logical_id}Role", "Arn"]} + ) + self.exp.add( + logical_id, "AWS::StepFunctions::StateMachine", machine, resource, meta(resource) + ) + if role is None: + self.iam.role( + f"{logical_id}Role", "states.amazonaws.com", [], policies, [], resource, extra + ) + events = p.pop("Events", None) or {} + for event_name, event in events.items() if isinstance(events, dict) else []: + self.event(logical_id, f"{logical_id}{event_name}", event or {}, resource) + self.exp.leftovers(logical_id, p) + + def event( + self, logical_id: str, event_id: str, event: dict[str, Any], resource: dict[str, Any] + ) -> None: + """One entry of the Events of a state machine: a rule or schedule that starts it.""" + kind = event.get("Type") + props = event.get("Properties") or {} + start = [statement(["states:StartExecution"], {"Ref": logical_id})] + if kind in ("Schedule", "EventBridgeRule", "CloudWatchEvent"): + role_id = f"{event_id}Role" + target = { + "Arn": {"Ref": logical_id}, + "Id": f"{event_id}StepFunctionsTarget", + "RoleArn": {"Fn::GetAtt": [role_id, "Arn"]}, + } + self.rules.rule(event_id, kind, props, target, resource) + self.iam.role( + role_id, + "events.amazonaws.com", + [], + None, + [inline_policy(f"{event_id}StartExecution", start)], + resource, + ) + elif kind == "ScheduleV2": + self.rules.schedule_v2( + event_id, props, {"Ref": logical_id}, "states:StartExecution", resource + ) + else: + self.exp.note(f"{event_id}: SAM state machine event type '{kind}' was not converted") + + +# --- connectors ------------------------------------------------------------------------- + + +class ConnectorExpander: + """AWS::Serverless::Connector (and the Connectors attribute of a resource): IAM + permissions, or a Lambda permission, between two resources of this template.""" + + def __init__(self, expansion: Expansion, iam: IamWriter) -> None: + """Write into `expansion`, with Lambda permissions from `iam`.""" + self.exp = expansion + self.iam = iam + + def expand(self, logical_id: str, props: dict[str, Any], source_id: str | None) -> None: + """One connector. `source_id` is the resource that embeds it, if any.""" + source_id = source_id or ref_id(props.get("Source")) + permissions = as_list(props.get("Permissions")) + destinations = as_list(props.get("Destination")) + for index, destination in enumerate(destinations): + destination_id = ref_id(destination) + # SAM names each destination policy separately when there are several. + name = f"{logical_id}PolicyDestination{index}" if len(destinations) > 1 else None + if source_id not in self.exp.source or destination_id not in self.exp.source: + self.exp.note( + f"{logical_id}: a connector end is outside this template; the connector " + "was not converted" + ) + continue + self.connect(logical_id, source_id, destination_id or "", permissions, name) + + def plain_type(self, logical_id: str) -> str: + """The CloudFormation type a source resource has once SAM expanded it.""" + kind = self.exp.source[logical_id]["Type"] + return SERVERLESS_TYPES.get(kind, kind) + + def connect( + self, + logical_id: str, + source_id: str, + destination_id: str, + permissions: list[str], + policy_name: str | None = None, + ) -> None: + """Grant `permissions` (Read, Write) from the source to one destination.""" + source_type = self.plain_type(source_id) + destination_type = self.plain_type(destination_id) + if destination_type == "AWS::Lambda::Function" and source_type in PRINCIPALS: + self.lambda_permission(logical_id, source_id, source_type, destination_id) + return + actions_by_permission = CONNECTOR_ACTIONS.get(destination_type) + source = self.exp.out.get(source_id) or {} + role_value = (source.get("Properties") or {}).get(ROLE_PROPERTY.get(source_type, "")) + role_id = role_value.get("Fn::GetAtt", [None])[0] if isinstance(role_value, dict) else None + role = self.exp.out.get(role_id) if isinstance(role_id, str) else None + actions = [a for p in permissions for a in (actions_by_permission or {}).get(str(p), [])] + if role is None or not actions: + self.exp.note( + f"{logical_id}: connector from {source_type} to {destination_type} was not " + "converted; grant the access by hand" + ) + return + if destination_type in REF_IS_ARN: + resources: list[Any] = [{"Ref": destination_id}] + else: + resources = [{"Fn::GetAtt": [destination_id, "Arn"]}] + if destination_type == "AWS::DynamoDB::Table": + resources.append( + sub("${arn}/index/*", {"arn": {"Fn::GetAtt": [destination_id, "Arn"]}}) + ) + elif destination_type == "AWS::S3::Bucket": + resources.append(sub("${arn}/*", {"arn": {"Fn::GetAtt": [destination_id, "Arn"]}})) + role["Properties"].setdefault("Policies", []).append( + inline_policy(policy_name or f"{logical_id}Policy", [statement(actions, resources)]) + ) + + def lambda_permission( + self, logical_id: str, source_id: str, source_type: str, destination_id: str + ) -> None: + """A source that calls a function through a resource-based permission.""" + source_arn: Any = {"Fn::GetAtt": [source_id, "Arn"]} + if source_type in ("AWS::ApiGateway::RestApi", "AWS::ApiGatewayV2::Api"): + source_arn = sub( + f"{PARTITION_ARN}:execute-api:${{AWS::Region}}:${{AWS::AccountId}}:${{api}}/*", + {"api": {"Ref": source_id}}, + ) + elif source_type == "AWS::SNS::Topic": + source_arn = {"Ref": source_id} + self.iam.permission( + f"{logical_id}WriteLambdaPermission", + {"Fn::GetAtt": [destination_id, "Arn"]}, + PRINCIPALS[source_type], + source_arn, + {}, + ) + + +# --- the whole expansion ---------------------------------------------------------------- + + +class SamExpander: + """Expands every AWS::Serverless::* resource of one template, in the order SAM does: + functions and other resources first, then the APIs (whose bodies collect the events of + every function), then connectors (which add to the generated roles).""" + + def __init__(self, template: dict[str, Any], notes: list[str]) -> None: + """`template` is changed in place; pass a copy.""" + self.exp = Expansion(template, notes) + iam = IamWriter(self.exp) + rules = RuleWriter(self.exp, iam) + self.functions = FunctionExpander(self.exp, iam, rules) + self.apis = ApiExpander(self.exp) + self.storage = StorageExpander(self.exp) + self.state_machines = StateMachineExpander(self.exp, iam, rules) + self.connectors = ConnectorExpander(self.exp, iam) + self.handlers: dict[str, Callable[[str, dict[str, Any]], None]] = { + "AWS::Serverless::Function": self.functions.expand, + "AWS::Serverless::SimpleTable": self.storage.simple_table, + "AWS::Serverless::LayerVersion": self.storage.layer, + "AWS::Serverless::StateMachine": self.state_machines.expand, + } + + def collect_generated_apis(self) -> None: + """Mark the APIs whose body SAM writes from function events.""" + for logical_id, resource in self.exp.source.items(): + props = resource.get("Properties") or {} + if "DefinitionBody" in props or "DefinitionUri" in props: + continue + if resource["Type"] == "AWS::Serverless::Api": + self.exp.rest_paths[logical_id] = {} + elif resource["Type"] == "AWS::Serverless::HttpApi": + self.exp.http_paths[logical_id] = {} + + def expand_resources( + self, connectors: list[tuple[str, dict[str, Any], str | None]], apis: list[str] + ) -> None: + """Expand every resource but APIs and connectors, which are collected into `apis` + and `connectors` for later.""" + for logical_id, resource in self.exp.source.items(): + kind = resource["Type"] + embedded = resource.pop("Connectors", None) + if isinstance(embedded, dict): + for name, connector in embedded.items(): + connectors.append( + ( + f"{logical_id}{name}", + (connector or {}).get("Properties") or {}, + logical_id, + ) + ) + if kind in self.handlers: + self.handlers[kind](logical_id, resource) + elif kind in ("AWS::Serverless::Api", "AWS::Serverless::HttpApi"): + # API bodies collect every event of every function, so APIs are built last. + # The placeholder keeps the resource order. + apis.append(logical_id) + self.exp.out[logical_id] = resource + elif kind == "AWS::Serverless::Connector": + connectors.append((logical_id, resource.get("Properties") or {}, None)) + elif kind.startswith("AWS::Serverless::"): + self.exp.note( + f"{logical_id} ({kind}) was not converted: Terraform has no equivalent; " + "convert it by hand" + ) + else: + self.exp.out[logical_id] = resource + + def expand_apis(self, apis: list[str]) -> None: + """The declared APIs, then the implicit ones function events asked for.""" + for logical_id in apis: + resource = self.exp.out[logical_id] + if resource["Type"] == "AWS::Serverless::Api": + self.apis.rest_api(logical_id, resource) + else: + self.apis.http_api(logical_id, resource) + if "ServerlessRestApi" in self.exp.rest_paths and "ServerlessRestApi" not in self.exp.out: + self.apis.rest_api("ServerlessRestApi", None) + if "ServerlessHttpApi" in self.exp.http_paths and "ServerlessHttpApi" not in self.exp.out: + self.apis.http_api("ServerlessHttpApi", None) + + def run(self) -> dict[str, Any]: + """Expand the template. Returns the plain CloudFormation template.""" + self.collect_generated_apis() + connectors: list[tuple[str, dict[str, Any], str | None]] = [] + apis: list[str] = [] + self.expand_resources(connectors, apis) + self.expand_apis(apis) + for logical_id, props, source in connectors: + self.connectors.expand(logical_id, props, source) + + original = self.exp.template + template = {k: v for k, v in original.items() if k not in ("Globals", "Transform")} + others = [t for t in as_list(original.get("Transform")) if t != SAM_TRANSFORM] + if others: + template["Transform"] = others + rewriter = ReferenceRewriter(self.exp.aliases) + template["Resources"] = rewriter.rewrite(self.exp.out) + if "Outputs" in template: + template["Outputs"] = rewriter.rewrite(template["Outputs"]) + return template + + +def expand_sam( + template: dict[str, Any], notes: list[str] +) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: + """Expand every AWS::Serverless::* resource. Returns (template, converter hints).""" + expander = SamExpander(copy.deepcopy(template), notes) + return expander.run(), expander.exp.hints diff --git a/services/converter-api/converters/cfn/sam_constants.py b/services/converter-api/converters/cfn/sam_constants.py new file mode 100644 index 0000000..27568c5 --- /dev/null +++ b/services/converter-api/converters/cfn/sam_constants.py @@ -0,0 +1,169 @@ +"""Names, property lists and IAM actions the SAM expansion uses.""" + +from __future__ import annotations + +import re + +PARTITION_ARN = "arn:${AWS::Partition}" +BASIC_EXECUTION = "service-role/AWSLambdaBasicExecutionRole" +GLOBAL_SECTIONS = { + "Function": "AWS::Serverless::Function", + "Api": "AWS::Serverless::Api", + "HttpApi": "AWS::Serverless::HttpApi", + "SimpleTable": "AWS::Serverless::SimpleTable", + "StateMachine": "AWS::Serverless::StateMachine", + "LayerVersion": "AWS::Serverless::LayerVersion", +} +# Resource attributes every generated resource inherits from the SAM resource. +INHERITED = ("Condition", "DeletionPolicy", "UpdateReplacePolicy") +S3_URI = re.compile(r"^s3://([^/]+)/(.+)$") +SUB_REFERENCE = re.compile(r"\$\{([A-Za-z0-9]+\.[A-Za-z]+)\}") +FUNCTION_PROPERTIES = ( + "FunctionName", + "Description", + "Handler", + "Runtime", + "MemorySize", + "Timeout", + "Environment", + "VpcConfig", + "Layers", + "Architectures", + "EphemeralStorage", + "KmsKeyArn", + "ReservedConcurrentExecutions", + "LoggingConfig", + "SnapStart", + "ImageConfig", + "FileSystemConfigs", + "PackageType", + "RuntimeManagementConfig", + "CodeSigningConfigArn", + "RecursiveLoop", +) + +# IAM actions of the SAM policy templates. +DYNAMODB_CRUD = ( + "dynamodb:GetItem", + "dynamodb:DeleteItem", + "dynamodb:PutItem", + "dynamodb:Scan", + "dynamodb:Query", + "dynamodb:UpdateItem", + "dynamodb:BatchWriteItem", + "dynamodb:BatchGetItem", + "dynamodb:DescribeTable", + "dynamodb:ConditionCheckItem", +) +DYNAMODB_READ = ( + "dynamodb:GetItem", + "dynamodb:Scan", + "dynamodb:Query", + "dynamodb:BatchGetItem", + "dynamodb:DescribeTable", +) +DYNAMODB_WRITE = ("dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:BatchWriteItem") +S3_READ = ( + "s3:GetObject", + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:GetObjectVersion", + "s3:GetLifecycleConfiguration", +) +S3_WRITE = ("s3:PutObject", "s3:PutObjectAcl", "s3:PutLifecycleConfiguration") +SQS_POLL = ( + "sqs:ChangeMessageVisibility", + "sqs:ChangeMessageVisibilityBatch", + "sqs:DeleteMessage", + "sqs:DeleteMessageBatch", + "sqs:GetQueueAttributes", + "sqs:ReceiveMessage", +) +SSM_READ = ("ssm:GetParameters", "ssm:GetParameter", "ssm:GetParametersByPath") +ENI = ( + "ec2:CreateNetworkInterface", + "ec2:DeleteNetworkInterface", + "ec2:DescribeNetworkInterfaces", + "ec2:DetachNetworkInterface", +) + +# Event sources that poll a stream or queue, and the managed policy SAM attaches for each. +POLLERS = { + "SQS": ("Queue", "service-role/AWSLambdaSQSQueueExecutionRole"), + "Kinesis": ("Stream", "service-role/AWSLambdaKinesisExecutionRole"), + "DynamoDB": ("Stream", "service-role/AWSLambdaDynamoDBExecutionRole"), +} +POLLER_PROPERTIES = ( + "BatchSize", + "Enabled", + "MaximumBatchingWindowInSeconds", + "FilterCriteria", + "FunctionResponseTypes", + "ScalingConfig", + "StartingPosition", + "StartingPositionTimestamp", + "MaximumRetryAttempts", + "MaximumRecordAgeInSeconds", + "BisectBatchOnFunctionError", + "ParallelizationFactor", + "TumblingWindowInSeconds", + "DestinationConfig", +) + +# The IAM actions a connector grants, by destination type and permission (Read, Write). +CONNECTOR_ACTIONS: dict[str, dict[str, list[str]]] = { + "AWS::DynamoDB::Table": { + "Read": [ + "dynamodb:GetItem", + "dynamodb:Query", + "dynamodb:Scan", + "dynamodb:BatchGetItem", + "dynamodb:ConditionCheckItem", + "dynamodb:PartiQLSelect", + ], + "Write": [ + "dynamodb:PutItem", + "dynamodb:UpdateItem", + "dynamodb:DeleteItem", + "dynamodb:BatchWriteItem", + "dynamodb:PartiQLDelete", + "dynamodb:PartiQLInsert", + "dynamodb:PartiQLUpdate", + ], + }, + "AWS::S3::Bucket": { + "Read": ["s3:GetObject", "s3:GetObjectVersion", "s3:ListBucket", "s3:GetObjectAcl"], + "Write": ["s3:PutObject", "s3:PutObjectAcl", "s3:DeleteObject", "s3:DeleteObjectVersion"], + }, + "AWS::SQS::Queue": { + "Read": ["sqs:ReceiveMessage", "sqs:GetQueueAttributes"], + "Write": ["sqs:SendMessage", "sqs:DeleteMessage", "sqs:ChangeMessageVisibility"], + }, + "AWS::SNS::Topic": {"Write": ["sns:Publish"]}, + "AWS::Lambda::Function": {"Write": ["lambda:InvokeFunction"], "Read": ["lambda:GetFunction"]}, + "AWS::StepFunctions::StateMachine": { + "Write": ["states:StartExecution", "states:StartSyncExecution"], + "Read": ["states:DescribeStateMachine", "states:ListExecutions"], + }, + "AWS::Events::EventBus": {"Write": ["events:PutEvents"]}, +} +# The plain CloudFormation type each serverless type expands to. +SERVERLESS_TYPES = { + "AWS::Serverless::Function": "AWS::Lambda::Function", + "AWS::Serverless::SimpleTable": "AWS::DynamoDB::Table", + "AWS::Serverless::StateMachine": "AWS::StepFunctions::StateMachine", + "AWS::Serverless::Api": "AWS::ApiGateway::RestApi", + "AWS::Serverless::HttpApi": "AWS::ApiGatewayV2::Api", +} +# Sources that call a function through a resource-based permission instead of a role. +PRINCIPALS = { + "AWS::ApiGateway::RestApi": "apigateway.amazonaws.com", + "AWS::ApiGatewayV2::Api": "apigateway.amazonaws.com", + "AWS::Events::Rule": "events.amazonaws.com", + "AWS::SNS::Topic": "sns.amazonaws.com", + "AWS::S3::Bucket": "s3.amazonaws.com", +} +# The property that holds the role of a connector source. +ROLE_PROPERTY = {"AWS::Lambda::Function": "Role", "AWS::StepFunctions::StateMachine": "RoleArn"} +# Ref gives the ARN for these; Fn::GetAtt Arn for the rest. +REF_IS_ARN = {"AWS::SNS::Topic", "AWS::StepFunctions::StateMachine"} diff --git a/services/converter-api/converters/cfn/sam_policies.py b/services/converter-api/converters/cfn/sam_policies.py new file mode 100644 index 0000000..811f972 --- /dev/null +++ b/services/converter-api/converters/cfn/sam_policies.py @@ -0,0 +1,270 @@ +"""IAM documents for the SAM expansion: Fn::Sub ARNs, statements and the SAM policy templates.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from converters.cfn.sam_constants import ( + DYNAMODB_CRUD, + DYNAMODB_READ, + DYNAMODB_WRITE, + ENI, + PARTITION_ARN, + S3_READ, + S3_WRITE, + SQS_POLL, + SSM_READ, +) + +PolicyTemplate = Callable[[dict[str, Any]], list[dict[str, Any]]] + + +def sub(text: str, variables: dict[str, Any] | None = None) -> dict[str, Any]: + """A Fn::Sub of `text`, with the variable map when there is one.""" + if variables: + return {"Fn::Sub": [text, variables]} + return {"Fn::Sub": text} + + +def arn(service: str, resource: str, variables: dict[str, Any] | None = None) -> dict[str, Any]: + """An ARN in this partition, region and account.""" + return sub( + f"{PARTITION_ARN}:{service}:${{AWS::Region}}:${{AWS::AccountId}}:{resource}", variables + ) + + +def managed_policy(name: str) -> Any: + """The ARN of an AWS managed policy given by name (or the ARN itself).""" + if name.startswith("arn:"): + return name + return sub(f"{PARTITION_ARN}:iam::aws:policy/{name}") + + +def statement(actions: list[str] | tuple[str, ...], resources: Any) -> dict[str, Any]: + """An Allow statement for `actions` on `resources` (one resource or a list).""" + return { + "Effect": "Allow", + "Action": list(actions), + "Resource": resources if isinstance(resources, list) else [resources], + } + + +def document(statements: list[dict[str, Any]]) -> dict[str, Any]: + """A policy document holding `statements`.""" + return {"Version": "2012-10-17", "Statement": statements} + + +def inline_policy(name: str, statements: list[dict[str, Any]]) -> dict[str, Any]: + """An inline policy of a role.""" + return {"PolicyName": name, "PolicyDocument": document(statements)} + + +class PolicyTemplates: + """The commonly used SAM policy templates as IAM statements. Each template takes its + parameters ({"TableName": ...}) and returns a list of statements.""" + + def __init__(self) -> None: + """The table of templates by SAM name.""" + self.by_name: dict[str, PolicyTemplate] = { + "DynamoDBCrudPolicy": self.dynamodb_crud, + "DynamoDBReadPolicy": self.dynamodb_read, + "DynamoDBWritePolicy": self.dynamodb_write, + "DynamoDBStreamReadPolicy": self.dynamodb_stream_read, + "S3ReadPolicy": self.s3_read, + "S3WritePolicy": self.s3_write, + "S3CrudPolicy": self.s3_crud, + "SQSPollerPolicy": self.sqs_poller, + "SQSSendMessagePolicy": self.sqs_send_message, + "SNSPublishMessagePolicy": self.sns_publish_message, + "LambdaInvokePolicy": self.lambda_invoke, + "StepFunctionsExecutionPolicy": self.step_functions_execution, + "EventBridgePutEventsPolicy": self.event_bridge_put_events, + "SSMParameterReadPolicy": self.ssm_parameter_read, + "SSMParameterWithSlashPrefixReadPolicy": self.ssm_parameter_with_slash_prefix_read, + "AWSSecretsManagerGetSecretValuePolicy": self.secrets_manager_get_secret_value, + "KMSDecryptPolicy": self.kms_decrypt, + "KMSEncryptPolicy": self.kms_encrypt, + "KinesisStreamReadPolicy": self.kinesis_stream_read, + "CloudWatchPutMetricPolicy": self.cloudwatch_put_metric, + "VPCAccessPolicy": self.vpc_access, + "AMIDescribePolicy": self.ami_describe, + "CloudFormationDescribeStacksPolicy": self.cloudformation_describe_stacks, + "FilterLogEventsPolicy": self.filter_log_events, + } + + def names(self) -> list[str]: + """Every supported template name, sorted.""" + return sorted(self.by_name) + + def get(self, name: str) -> PolicyTemplate | None: + """The template called `name`, or None for one this converter does not know.""" + return self.by_name.get(name) + + # --- ARN helpers ------------------------------------------------------------------ + + def table(self, params: dict[str, Any], suffix: str = "") -> Any: + """The ARN of the TableName table, with `suffix` (/index/*, /stream/*).""" + return arn( + "dynamodb", "table/${tableName}" + suffix, {"tableName": params.get("TableName")} + ) + + def bucket(self, params: dict[str, Any], suffix: str = "") -> Any: + """The ARN of the BucketName bucket, with `suffix` (/*).""" + return sub( + f"{PARTITION_ARN}:s3:::${{bucketName}}{suffix}", + {"bucketName": params.get("BucketName")}, + ) + + def named(self, service: str, resource: str, value: Any) -> Any: + """The ARN of `resource`, where `${name}` is `value` (a template parameter).""" + return arn(service, resource, {"name": value}) + + def single( + self, + actions: list[str] | tuple[str, ...], + service: str, + resource: str, + value: Any, + ) -> list[dict[str, Any]]: + """One statement for `actions` on the ARN that `named` builds.""" + return [statement(actions, self.named(service, resource, value))] + + # --- the templates ---------------------------------------------------------------- + + def dynamodb_crud(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """DynamoDBCrudPolicy.""" + return [statement(DYNAMODB_CRUD, [self.table(p), self.table(p, "/index/*")])] + + def dynamodb_read(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """DynamoDBReadPolicy.""" + return [statement(DYNAMODB_READ, [self.table(p), self.table(p, "/index/*")])] + + def dynamodb_write(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """DynamoDBWritePolicy.""" + return [statement(DYNAMODB_WRITE, [self.table(p), self.table(p, "/index/*")])] + + def dynamodb_stream_read(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """DynamoDBStreamReadPolicy.""" + return [ + statement( + ["dynamodb:DescribeStream", "dynamodb:GetRecords", "dynamodb:GetShardIterator"], + arn( + "dynamodb", + "table/${tableName}/stream/${streamName}", + {"tableName": p.get("TableName"), "streamName": p.get("StreamName")}, + ), + ), + statement(["dynamodb:ListStreams"], self.table(p, "/stream/*")), + ] + + def s3_read(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """S3ReadPolicy.""" + return [statement(S3_READ, [self.bucket(p), self.bucket(p, "/*")])] + + def s3_write(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """S3WritePolicy.""" + return [statement(S3_WRITE, [self.bucket(p), self.bucket(p, "/*")])] + + def s3_crud(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """S3CrudPolicy.""" + actions = S3_READ + S3_WRITE + ("s3:DeleteObject",) + return [statement(actions, [self.bucket(p), self.bucket(p, "/*")])] + + def sqs_poller(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """SQSPollerPolicy.""" + return self.single(SQS_POLL, "sqs", "${name}", p.get("QueueName")) + + def sqs_send_message(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """SQSSendMessagePolicy.""" + return self.single(["sqs:SendMessage*"], "sqs", "${name}", p.get("QueueName")) + + def sns_publish_message(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """SNSPublishMessagePolicy.""" + return self.single(["sns:Publish"], "sns", "${name}", p.get("TopicName")) + + def lambda_invoke(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """LambdaInvokePolicy.""" + return self.single( + ["lambda:InvokeFunction"], "lambda", "function:${name}*", p.get("FunctionName") + ) + + def step_functions_execution(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """StepFunctionsExecutionPolicy.""" + return self.single( + ["states:StartExecution"], "states", "stateMachine:${name}", p.get("StateMachineName") + ) + + def event_bridge_put_events(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """EventBridgePutEventsPolicy.""" + return self.single( + ["events:PutEvents"], "events", "event-bus/${name}", p.get("EventBusName") + ) + + def ssm_parameter_read(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """SSMParameterReadPolicy.""" + return [ + statement(["ssm:DescribeParameters"], "*"), + statement(SSM_READ, self.named("ssm", "parameter/${name}", p.get("ParameterName"))), + ] + + def ssm_parameter_with_slash_prefix_read(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """SSMParameterWithSlashPrefixReadPolicy.""" + return [ + statement(["ssm:DescribeParameters"], "*"), + statement(SSM_READ, self.named("ssm", "parameter${name}", p.get("ParameterName"))), + ] + + def secrets_manager_get_secret_value(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """AWSSecretsManagerGetSecretValuePolicy.""" + return [statement(["secretsmanager:GetSecretValue"], p.get("SecretArn"))] + + def kms_decrypt(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """KMSDecryptPolicy.""" + return self.single(["kms:Decrypt"], "kms", "key/${name}", p.get("KeyId")) + + def kms_encrypt(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """KMSEncryptPolicy.""" + return self.single(["kms:Encrypt"], "kms", "key/${name}", p.get("KeyId")) + + def kinesis_stream_read(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """KinesisStreamReadPolicy.""" + return [ + statement( + ["kinesis:ListStreams", "kinesis:DescribeLimits"], arn("kinesis", "stream/*") + ), + statement( + [ + "kinesis:DescribeStream", + "kinesis:DescribeStreamSummary", + "kinesis:GetRecords", + "kinesis:GetShardIterator", + ], + self.named("kinesis", "stream/${name}", p.get("StreamName")), + ), + ] + + def cloudwatch_put_metric(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """CloudWatchPutMetricPolicy (no parameters).""" + return [statement(["cloudwatch:PutMetricData"], "*")] + + def vpc_access(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """VPCAccessPolicy (no parameters).""" + return [statement(ENI, "*")] + + def ami_describe(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """AMIDescribePolicy (no parameters).""" + return [statement(["ec2:DescribeImages"], "*")] + + def cloudformation_describe_stacks(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """CloudFormationDescribeStacksPolicy (no parameters).""" + return [statement(["cloudformation:DescribeStacks"], arn("cloudformation", "stack/*"))] + + def filter_log_events(self, p: dict[str, Any]) -> list[dict[str, Any]]: + """FilterLogEventsPolicy.""" + return self.single( + ["logs:FilterLogEvents"], + "logs", + "log-group:${name}:log-stream:*", + p.get("LogGroupName"), + ) diff --git a/services/converter-api/converters/compose_constants.py b/services/converter-api/converters/compose_constants.py new file mode 100644 index 0000000..237a8b2 --- /dev/null +++ b/services/converter-api/converters/compose_constants.py @@ -0,0 +1,57 @@ +"""Names, limits and defaults of the compose to Kubernetes conversion and its renderers.""" + +from __future__ import annotations + +import re + +# K8s Service names must be DNS-1035 labels: lowercase alphanumerics and '-', starting with a +# letter, max 63 chars. Deployments get the same name so labels and selectors line up. +DNS_LABEL_MAX = 63 +INVALID_NAME_CHARS = re.compile(r"[^a-z0-9-]+") +NAME_PREFIX = "svc-" + +# Deployment spec.replicas is an int32. +MAX_REPLICAS = 2**31 - 1 +DIGITS = re.compile(r"[0-9]+") + +# Compose memory units -> K8s binary suffixes. Docker treats these as powers of 1024. +MEMORY_UNITS = { + "b": "", + "k": "Ki", + "kb": "Ki", + "m": "Mi", + "mb": "Mi", + "g": "Gi", + "gb": "Gi", +} +# Applied to a stripped value. No two adjacent repetitions can match the same character, so +# matching stays linear however long the input is. +MEMORY_PATTERN = re.compile(r"^([0-9]+(?:\.[0-9]+)?)[ \t]*([a-zA-Z]*)$") + +# Placeholder resources, added when a service declares none. Kubernetes schedules an +# unbounded pod otherwise; the note tells the user these are starting points. +DEFAULT_REQUESTS = {"cpu": "100m", "memory": "128Mi"} +DEFAULT_LIMITS = {"cpu": "500m", "memory": "512Mi"} +# Named volumes become PersistentVolumeClaims of this size; the note says to adjust it. +DEFAULT_VOLUME_SIZE = "1Gi" +# Init containers that wait for the port of a dependency. Pinned, tiny, has `nc`. +WAIT_IMAGE = "busybox:1.37" + +DURATION = re.compile(r"(\d+(?:\.\d+)?)(ms|us|µs|ns|h|m|s)") +DURATION_SECONDS = {"ns": 1e-9, "us": 1e-6, "µs": 1e-6, "ms": 1e-3, "s": 1, "m": 60, "h": 3600} +BIND_PREFIXES = ("/", "./", "../", "~") +# Manifest kinds in apply order: a namespace before what goes in it, storage before the +# workloads that mount it, workloads before their Services. +MANIFEST_ORDER = ("namespaces", "persistent_volume_claims", "deployments", "services") + +# Renderers (render.py). +OUTPUTS = ("manifests", "helm") +FILE_SUFFIX = { + "namespaces": "namespace", + "persistent_volume_claims": "pvc", + "deployments": "deployment", + "services": "service", +} +CHART_NAME_INVALID = re.compile(r"[^a-z0-9-]+") +# Sentinels: dumped by PyYAML as plain text, then swapped for Helm template expressions. +SENTINEL = "__HELM_{kind}_{name}__" diff --git a/services/converter-api/converters/compose_to_k8s.py b/services/converter-api/converters/compose_to_k8s.py index c3999a7..4e37b63 100644 --- a/services/converter-api/converters/compose_to_k8s.py +++ b/services/converter-api/converters/compose_to_k8s.py @@ -22,114 +22,30 @@ import yaml -# K8s Service names must be DNS-1035 labels: lowercase alphanumerics and '-', starting with a -# letter, max 63 chars. Deployments get the same name so labels and selectors line up. -_DNS_LABEL_MAX = 63 -_INVALID_NAME_CHARS = re.compile(r"[^a-z0-9-]+") -_NAME_PREFIX = "svc-" - -# Upper bound on YAML values, both as written and after aliases are expanded. A real compose -# file has a few hundred; this stops oversized or "billion laughs" input from eating CPU. -MAX_NODES = 10_000 - -# Real compose files nest lists/mappings fewer than 10 levels deep. -MAX_DEPTH = 100 - -# libyaml's C parser ships in the PyYAML wheel and is 10-100x faster than the pure-Python -# one (50,000 nested brackets: ~3ms vs ~0.3s). Fall back if PyYAML was built without it. -_FAST_LOADER = getattr(yaml, "CSafeLoader", yaml.SafeLoader) - -# Deployment spec.replicas is an int32. -_MAX_REPLICAS = 2**31 - 1 - -_NULL_TAG = "tag:yaml.org,2002:null" -_MERGE_TAG = "tag:yaml.org,2002:merge" -_DIGITS = re.compile(r"[0-9]+") - - -class SafeMergeLoader(_FAST_LOADER): - """Safe loader whose `<<` merge keys cost linear, not exponential, time. - - PyYAML copies every merged key/value pair once per reference before de-duplicating, so - `a2: {<<: [*a1, *a1, ...]}` chained a few levels deep grows 9x per level (a 500-char - input can take minutes). Dropping duplicate keys after each merge keeps it linear. The - last occurrence of a key wins, which is the same result PyYAML gives. - """ - - def flatten_mapping(self, node: yaml.MappingNode) -> None: - super().flatten_mapping(node) - seen: set[tuple[str, str]] = set() - kept: list[tuple[yaml.Node, yaml.Node]] = [] - for key_node, value_node in reversed(node.value): - if isinstance(key_node, yaml.ScalarNode): - key = (key_node.tag, key_node.value) - if key in seen: - continue - seen.add(key) - kept.append((key_node, value_node)) - kept.reverse() - node.value = kept - - -class _ComposeLoader(SafeMergeLoader): - """Loader that keeps plain scalars as strings, except null and '<<' merge keys. - - PyYAML follows YAML 1.1, where `on` means True, `0755` is octal 493 and an unquoted - `22:22` is the base-60 number 1342. Compose uses YAML 1.2, so those values must reach - the container unchanged. Keeping the text as-is gives the same result, and numeric - fields (ports, replicas, cpus) are converted explicitly below. - """ - - -_ComposeLoader.yaml_implicit_resolvers = { - first_char: [(tag, regexp) for tag, regexp in resolvers if tag in (_NULL_TAG, _MERGE_TAG)] - for first_char, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items() -} - - -def _load_yaml(text: str, loader_class: type[yaml.SafeLoader]) -> Any: - """Build the single document in `text` with one of the safe loaders above. - - This is what yaml.load() does internally, spelled out so the loader is visibly a - SafeLoader subclass: it can only build the standard YAML types (mappings, lists, - strings, numbers, booleans, null), never arbitrary Python objects. - """ - loader = loader_class(text) - try: - return loader.get_single_data() - finally: - loader.dispose() - - -def load_yaml_documents(text: str) -> list[Any]: - """Build every document in a multi-document YAML string (separated by ---). - - Uses SafeMergeLoader: safe types only, and linear-time `<<` merges. Raises yaml.YAMLError - on syntax errors. - """ - loader = SafeMergeLoader(text) - try: - documents: list[Any] = [] - while loader.check_data(): - documents.append(loader.get_data()) - return documents - finally: - loader.dispose() - - -# Compose memory units -> K8s binary suffixes. Docker treats these as powers of 1024. -_MEMORY_UNITS = { - "b": "", - "k": "Ki", - "kb": "Ki", - "m": "Mi", - "mb": "Mi", - "g": "Gi", - "gb": "Gi", -} -# Applied to a stripped value. No two adjacent repetitions can match the same character, so -# matching stays linear however long the input is. -_MEMORY_PATTERN = re.compile(r"^([0-9]+(?:\.[0-9]+)?)[ \t]*([a-zA-Z]*)$") +from converters.compose_constants import ( + BIND_PREFIXES, + DEFAULT_LIMITS, + DEFAULT_REQUESTS, + DEFAULT_VOLUME_SIZE, + DIGITS, + DNS_LABEL_MAX, + DURATION, + DURATION_SECONDS, + INVALID_NAME_CHARS, + MANIFEST_ORDER, + MAX_REPLICAS, + MEMORY_PATTERN, + MEMORY_UNITS, + NAME_PREFIX, + WAIT_IMAGE, +) +from converters.yaml_safety import ( + PlainScalarLoader, + YamlLimitError, + check_node_count, + check_yaml_limits, + load_single, +) class ComposeError(ValueError): @@ -140,6 +56,7 @@ class ComposeError(ValueError): """ def __init__(self, message: str, line: int | None = None, column: int | None = None) -> None: + """The user text, and the position in the input for a YAML syntax error.""" super().__init__(message) self.message = message # 1-based position in the input, when the error is a YAML syntax error. @@ -158,9 +75,12 @@ def parse_compose(yaml_string: str) -> dict[str, Any]: try: check_yaml_limits(yaml_string) - data = _load_yaml(yaml_string, _ComposeLoader) + data = load_single(yaml_string, PlainScalarLoader) + check_node_count(data) + except YamlLimitError as exc: + raise ComposeError(exc.message) from exc except yaml.YAMLError as exc: - # `problem` is the parser's description of the input ("mapping values are not + # `problem` is the description of the input by the parser ("mapping values are not # allowed here"). Nothing else from the exception reaches the user. problem = getattr(exc, "problem", None) or "syntax error" mark = getattr(exc, "problem_mark", None) @@ -168,8 +88,6 @@ def parse_compose(yaml_string: str) -> dict[str, Any]: column = mark.column + 1 if mark is not None else None raise ComposeError(f"Invalid YAML: {problem}", line, column) from exc - check_node_count(data) - if not isinstance(data, dict): raise ComposeError("Invalid compose file: top level must be a mapping") @@ -186,67 +104,22 @@ def parse_compose(yaml_string: str) -> dict[str, Any]: return data -def check_yaml_limits(text: str, max_depth: int = MAX_DEPTH, max_nodes: int = MAX_NODES) -> None: - """Raise ComposeError if YAML nests deeper than `max_depth` or has over `max_nodes` values. - - Building objects is the expensive part of loading YAML, and it recurses, so `[[[[...]]]]` - thousands deep or a 60 KB list of 30,000 items costs about a second of CPU. The parser's - event stream is flat and runs in C, so checking it first rejects both in milliseconds. - Aliases are counted once here; check_node_count() covers their expanded size. - - Raises yaml.YAMLError for syntax errors, so callers can report them as usual. - """ - depth = 0 - nodes = 0 - for event in yaml.parse(text, Loader=_FAST_LOADER): - if isinstance(event, yaml.NodeEvent): - nodes += 1 - if nodes > max_nodes: - raise ComposeError(f"Input too large: more than {max_nodes} values") - if isinstance(event, yaml.CollectionStartEvent): - depth += 1 - if depth > max_depth: - raise ComposeError("Invalid YAML: nested too deeply") - elif isinstance(event, yaml.CollectionEndEvent): - depth -= 1 - - -def check_node_count(data: Any, limit: int = MAX_NODES) -> None: - """Raise ComposeError if `data` has more than `limit` nodes once aliases are expanded. - - Stops counting as soon as the limit is passed, so even a huge alias bomb is rejected fast. - """ - count = 0 - stack = [data] - while stack: - node = stack.pop() - count += 1 - if count > limit: - raise ComposeError( - f"Input too large: more than {limit} values after expanding YAML aliases" - ) - if isinstance(node, dict): - stack.extend(node.keys()) - stack.extend(node.values()) - elif isinstance(node, list): - stack.extend(node) - - def to_k8s_name(name: str) -> str: """Turn a compose service name into a valid K8s object name. 'My_App' -> 'my-app'. Names must start with a letter, so '1api' -> 'svc-1api'. """ - cleaned = _INVALID_NAME_CHARS.sub("-", str(name).lower()).strip("-") + cleaned = INVALID_NAME_CHARS.sub("-", str(name).lower()).strip("-") if cleaned and not cleaned[0].isalpha(): - cleaned = _NAME_PREFIX + cleaned - cleaned = cleaned[:_DNS_LABEL_MAX].rstrip("-") + cleaned = NAME_PREFIX + cleaned + cleaned = cleaned[:DNS_LABEL_MAX].rstrip("-") if not cleaned: raise ComposeError(f"Service name '{name}' cannot be turned into a valid K8s name") return cleaned def _expect_list(value: Any, field: str, service: str) -> list[Any]: + """`value` of `field` as a list: [] for None, an error for anything else.""" if value is None: return [] if not isinstance(value, list): @@ -255,6 +128,7 @@ def _expect_list(value: Any, field: str, service: str) -> list[Any]: def _expect_mapping(value: Any, field: str, service: str) -> dict[str, Any]: + """`value` of `field` as a mapping: {} for None, an error for anything else.""" if value is None: return {} if not isinstance(value, dict): @@ -298,6 +172,7 @@ def parse_ports(ports: list[Any] | None) -> list[dict[str, Any]]: def _port(container: Any, published: Any, protocol: str, raw: Any) -> dict[str, Any]: + """One checked port mapping; `raw` is the compose entry, for error messages.""" try: container_port = int(container) service_port = int(published) @@ -349,6 +224,7 @@ def parse_environment(environment: list[Any] | dict[str, Any] | None) -> list[di def _env_value(value: Any) -> str: + """An environment value as the text the container gets.""" if value is None: return "" if isinstance(value, bool): @@ -362,12 +238,12 @@ def convert_memory(value: Any) -> str: '512M' -> '512Mi', '1g' -> '1Gi', 268435456 (bytes) -> '256Mi'. """ - match = _MEMORY_PATTERN.match(str(value).strip()) + match = MEMORY_PATTERN.match(str(value).strip()) if not match: raise ComposeError(f"Invalid memory value: '{value}'") number, unit = match.groups() unit = unit.lower() - if unit not in _MEMORY_UNITS and unit != "": + if unit not in MEMORY_UNITS and unit != "": raise ComposeError(f"Unknown memory unit in '{value}'") if unit in ("", "b"): # Decimal, not float: a 400-digit number would otherwise become inf and crash int(). @@ -375,7 +251,7 @@ def convert_memory(value: Any) -> str: if number_bytes % (1024 * 1024) == 0: return f"{number_bytes // (1024 * 1024)}Mi" return str(number_bytes) - return f"{number}{_MEMORY_UNITS[unit]}" + return f"{number}{MEMORY_UNITS[unit]}" def convert_cpus(value: Any) -> str: @@ -398,6 +274,7 @@ def convert_cpus(value: Any) -> str: def _convert_resource_block(block: Any, field: str, service: str) -> dict[str, str]: + """A deploy.resources limits or reservations block as K8s cpu and memory.""" block = _expect_mapping(block, field, service) resources: dict[str, str] = {} if block.get("cpus") is not None: @@ -408,6 +285,7 @@ def _convert_resource_block(block: Any, field: str, service: str) -> dict[str, s def _command_list(value: Any, field: str, service: str) -> list[str]: + """`entrypoint` or `command` as a list: a list as it is, a string split like a shell.""" if isinstance(value, list): return [str(part) for part in value] try: @@ -417,36 +295,23 @@ def _command_list(value: Any, field: str, service: str) -> list[str]: def _parse_replicas(value: Any, service: str) -> int: + """deploy.replicas as a checked int32.""" text = str(value).strip() # Not str.isdigit(): that accepts '²' and other characters int() rejects. - if isinstance(value, bool) or not _DIGITS.fullmatch(text): + if isinstance(value, bool) or not DIGITS.fullmatch(text): raise ComposeError(f"Service '{service}' has an invalid replicas value: '{value}'") replicas = int(text) - if replicas > _MAX_REPLICAS: + if replicas > MAX_REPLICAS: raise ComposeError(f"Service '{service}' has too many replicas: {replicas}") return replicas def _service_ports(name: str, config: dict[str, Any]) -> list[dict[str, Any]]: - """All port mappings from a service's `ports` and `expose` lists.""" + """All port mappings from the `ports` and `expose` lists of a service.""" ports = parse_ports(_expect_list(config.get("ports"), "ports", name)) return ports + parse_ports(_expect_list(config.get("expose"), "expose", name)) -# Placeholder resources, added when a service declares none. Kubernetes schedules an -# unbounded pod otherwise; the note tells the user these are starting points. -DEFAULT_REQUESTS = {"cpu": "100m", "memory": "128Mi"} -DEFAULT_LIMITS = {"cpu": "500m", "memory": "512Mi"} -# Named volumes become PersistentVolumeClaims of this size; the note says to adjust it. -DEFAULT_VOLUME_SIZE = "1Gi" -# Init containers that wait for a dependency's port. Pinned, tiny, has `nc`. -WAIT_IMAGE = "busybox:1.37" - -_DURATION = re.compile(r"(\d+(?:\.\d+)?)(ms|us|µs|ns|h|m|s)") -_DURATION_SECONDS = {"ns": 1e-9, "us": 1e-6, "µs": 1e-6, "ms": 1e-3, "s": 1, "m": 60, "h": 3600} -_BIND_PREFIXES = ("/", "./", "../", "~") - - def _is_true(value: Any) -> bool: """Compose booleans. The loader keeps scalars as text, so `true` arrives as "true".""" if isinstance(value, bool): @@ -463,10 +328,10 @@ def parse_duration(value: Any, field: str, service: str) -> int: if re.fullmatch(r"\d+(?:\.\d+)?", text): seconds = float(text) else: - matches = _DURATION.findall(text) + matches = DURATION.findall(text) if not text or "".join(n + u for n, u in matches) != text.replace(" ", ""): raise ComposeError(f"Service '{service}': invalid duration in '{field}': '{value}'") - seconds = sum(float(n) * _DURATION_SECONDS[u] for n, u in matches) + seconds = sum(float(n) * DURATION_SECONDS[u] for n, u in matches) if not math.isfinite(seconds) or seconds <= 0: raise ComposeError(f"Service '{service}': invalid duration in '{field}': '{value}'") return max(1, math.ceil(seconds)) @@ -509,7 +374,7 @@ def convert_healthcheck(name: str, config: dict[str, Any]) -> dict[str, Any] | N if check.get("retries") is not None: retries = check["retries"] text = str(retries).strip() - if isinstance(retries, bool) or not _DIGITS.fullmatch(text) or int(text) < 1: + if isinstance(retries, bool) or not DIGITS.fullmatch(text) or int(text) < 1: raise ComposeError(f"Service '{name}': invalid healthcheck.retries: '{retries}'") probe["failureThreshold"] = int(text) if check.get("start_period") is not None: @@ -520,8 +385,30 @@ def convert_healthcheck(name: str, config: dict[str, Any]) -> dict[str, Any] | N def _mount_name(target: str) -> str: - cleaned = _INVALID_NAME_CHARS.sub("-", target.lower()).strip("-") - return (cleaned or "data")[:_DNS_LABEL_MAX].rstrip("-") + """A pod volume name from a mount path.""" + cleaned = INVALID_NAME_CHARS.sub("-", target.lower()).strip("-") + return (cleaned or "data")[:DNS_LABEL_MAX].rstrip("-") + + +class PodVolumes: + """The pod volumes and container mounts of one service. The same volume mounted at + two paths is one pod volume with two mounts.""" + + def __init__(self) -> None: + """No volumes yet.""" + self.volumes: list[dict[str, Any]] = [] + self.mounts: list[dict[str, Any]] = [] + self.used: set[str] = set() + + def add(self, volume: dict[str, Any], target: str, read_only: bool) -> None: + """Mount `volume` at `target`, adding it to the pod the first time.""" + if volume["name"] not in self.used: + self.used.add(volume["name"]) + self.volumes.append(volume) + mount: dict[str, Any] = {"name": volume["name"], "mountPath": target} + if read_only: + mount["readOnly"] = True + self.mounts.append(mount) def convert_volumes( @@ -534,22 +421,9 @@ def convert_volumes( equivalent and are reported as notes. """ entries = _expect_list(config.get("volumes"), "volumes", name) - volumes: list[dict[str, Any]] = [] - mounts: list[dict[str, Any]] = [] + pod = PodVolumes() claims: list[str] = [] notes: list[str] = [] - used: set[str] = set() - - def add(volume: dict[str, Any], target: str, read_only: bool) -> None: - # The same volume mounted at two paths is one pod volume with two mounts. - if volume["name"] not in used: - used.add(volume["name"]) - volumes.append(volume) - mount: dict[str, Any] = {"name": volume["name"], "mountPath": target} - if read_only: - mount["readOnly"] = True - mounts.append(mount) - for entry in entries: if isinstance(entry, dict): kind = str(entry.get("type", "volume")) @@ -566,7 +440,7 @@ def add(volume: dict[str, Any], target: str, read_only: bool) -> None: elif len(parts) in (2, 3): source, target = parts[0], parts[1] read_only = len(parts) == 3 and "ro" in parts[2].split(",") - kind = "bind" if source.startswith(_BIND_PREFIXES) else "volume" + kind = "bind" if source.startswith(BIND_PREFIXES) else "volume" else: raise ComposeError(f"Service '{name}': invalid volume entry '{entry}'") if not target.startswith("/"): @@ -577,12 +451,12 @@ def add(volume: dict[str, Any], target: str, read_only: bool) -> None: if kind == "bind": notes.append( f"'{name}' bind mount '{source}:{target}' was not converted: Kubernetes has no " - "host paths; use a ConfigMap, bake it into the image, or a PersistentVolumeClaim" + "host paths; use a ConfigMap, bake it into the image or use a PersistentVolumeClaim" ) elif kind == "tmpfs": - add({"name": _mount_name(target), "emptyDir": {"medium": "Memory"}}, target, False) + pod.add({"name": _mount_name(target), "emptyDir": {"medium": "Memory"}}, target, False) elif kind == "volume" and not source: - add({"name": _mount_name(target), "emptyDir": {}}, target, read_only) + pod.add({"name": _mount_name(target), "emptyDir": {}}, target, read_only) elif kind == "volume": claim = to_k8s_name(str(source)) spec = declared.get(str(source)) if isinstance(declared, dict) else None @@ -595,16 +469,18 @@ def add(volume: dict[str, Any], target: str, read_only: bool) -> None: ) else: claims.append(claim) - add({"name": claim, "persistentVolumeClaim": {"claimName": claim}}, target, read_only) + pod.add( + {"name": claim, "persistentVolumeClaim": {"claimName": claim}}, target, read_only + ) else: notes.append(f"'{name}' volume type '{kind}' is not supported and was skipped") - return volumes, mounts, claims, notes + return pod.volumes, pod.mounts, claims, notes def convert_depends_on( name: str, config: dict[str, Any], services: dict[str, Any], include_service: bool ) -> tuple[list[dict[str, Any]], list[str]]: - """Compose `depends_on` -> init containers that wait for each dependency's first port. + """Compose `depends_on` -> init containers that wait for the first port of each dependency. Kubernetes starts pods in any order; an init container that blocks until the dependency answers on its Service port gives the same effect. Dependencies without ports (or when @@ -631,13 +507,13 @@ def convert_depends_on( why = "has no ports" if include_service else "has no Service (Services were disabled)" notes.append( f"'{name}' depends on '{dep}', which {why}: nothing to wait for, so no init " - "container was added; make '{name}' retry its connection" + f"container was added; make '{name}' retry its connection" ) continue port = ports[0]["service_port"] inits.append( { - "name": f"wait-for-{dep_name}"[:_DNS_LABEL_MAX].rstrip("-"), + "name": f"wait-for-{dep_name}"[:DNS_LABEL_MAX].rstrip("-"), "image": WAIT_IMAGE, "command": ["sh", "-c", f"until nc -z {dep_name} {port}; do sleep 2; done"], } @@ -766,6 +642,7 @@ def convert_service_to_deployment( def persistent_volume_claim( name: str, namespace: str, size: str = DEFAULT_VOLUME_SIZE ) -> dict[str, Any]: + """A ReadWriteOnce PersistentVolumeClaim of `size`.""" return { "apiVersion": "v1", "kind": "PersistentVolumeClaim", @@ -775,13 +652,14 @@ def persistent_volume_claim( def namespace_manifest(namespace: str) -> dict[str, Any]: + """A Namespace manifest.""" return {"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": namespace}} def convert_service_to_k8s_service( name: str, config: dict[str, Any] | None, namespace: str = "default" ) -> dict[str, Any] | None: - """Build a ClusterIP Service for a compose service's ports. Returns None if it has no ports.""" + """Build a ClusterIP Service for the ports of a compose service, or None without ports.""" config = config or {} ports = _service_ports(name, config) if not ports: @@ -831,8 +709,8 @@ def _service_notes(name: str, config: dict[str, Any]) -> list[str]: ) if config.get("networks"): notes.append( - f"'{name}' uses networks: not needed in Kubernetes, services reach each other " - "by name (e.g. http://db:5432)" + f"'{name}' uses networks: Kubernetes services reach each other by name " + "(e.g. http://db:5432), so the networks were left out" ) if config.get("env_file"): notes.append(f"'{name}' uses env_file: move those values into a ConfigMap or Secret") @@ -850,7 +728,7 @@ def convert_compose_to_k8s( ) -> dict[str, Any]: """Convert a parsed compose file into K8s manifests. - Output is proportional to the input: a Namespace only when it isn't `default`, a + Output is proportional to the input: a Namespace only when it is not `default`, a PersistentVolumeClaim per named volume, a Deployment per service, and a Service per service with ports. @@ -907,7 +785,7 @@ def convert_compose_to_k8s( if len(users) > 1: notes.append( f"'{claim}' is mounted by more than one service: with ReadWriteOnce they must run " - "on the same node; use ReadWriteMany storage if they can't" + "on the same node; use ReadWriteMany storage if they cannot" ) namespaces = [] if namespace == "default" else [namespace_manifest(namespace)] @@ -925,9 +803,5 @@ def convert_compose_to_k8s( def manifests_to_yaml(manifests: dict[str, list[dict[str, Any]]]) -> str: """Render manifests as one multi-document YAML string, in apply order: Namespace, PersistentVolumeClaims, Deployments, Services.""" - documents = [ - doc - for kind in ("namespaces", "persistent_volume_claims", "deployments", "services") - for doc in manifests.get(kind, []) - ] + documents = [doc for kind in MANIFEST_ORDER for doc in manifests.get(kind, [])] return yaml.safe_dump_all(documents, sort_keys=False, default_flow_style=False) diff --git a/services/converter-api/converters/render.py b/services/converter-api/converters/render.py index ffbc9cf..d9ef20d 100644 --- a/services/converter-api/converters/render.py +++ b/services/converter-api/converters/render.py @@ -12,23 +12,15 @@ import yaml +from converters.compose_constants import ( + CHART_NAME_INVALID, + FILE_SUFFIX, + MANIFEST_ORDER, + OUTPUTS, + SENTINEL, +) from converters.compose_to_k8s import ComposeError, to_k8s_name -OUTPUTS = ("manifests", "helm") -# Resource kinds in the order the files are listed and applied: a namespace before what -# goes in it, storage before the workloads that mount it, workloads before their Services. -_ORDER = ("namespaces", "persistent_volume_claims", "deployments", "services") -_FILE_SUFFIX = { - "namespaces": "namespace", - "persistent_volume_claims": "pvc", - "deployments": "deployment", - "services": "service", -} -_CHART_NAME_INVALID = re.compile(r"[^a-z0-9-]+") - -# Sentinels: dumped by PyYAML as plain text, then swapped for Helm template expressions. -_SENTINEL = "__HELM_{kind}_{name}__" - def render_files( result: dict[str, Any], output: str = "manifests", chart_name: str | None = None @@ -43,148 +35,179 @@ def render_files( manifests = result["manifests"] if output == "manifests": return [ - {"path": _file_name(kind, resource), "content": _dump(resource)} - for kind in _ORDER + {"path": file_name(kind, resource), "content": dump(resource)} + for kind in MANIFEST_ORDER for resource in manifests.get(kind, []) ] - return _render_chart(manifests, chart_name or "app") + return HelmChart(manifests, chart_name or "app").render() -def _file_name(kind: str, resource: dict[str, Any]) -> str: - return f"{resource['metadata']['name']}-{_FILE_SUFFIX[kind]}.yaml" +def file_name(kind: str, resource: dict[str, Any]) -> str: + """The file name of one manifest: -.yaml.""" + return f"{resource['metadata']['name']}-{FILE_SUFFIX[kind]}.yaml" -def _dump(document: Any) -> str: +def dump(document: Any) -> str: + """One YAML document, keys in the order they were built.""" return yaml.safe_dump(document, sort_keys=False, default_flow_style=False) def chart_name_from(compose: dict[str, Any]) -> str: - """A chart name from the compose file's top-level `name`, or 'app'.""" + """A chart name from the top-level `name` of the compose file, or 'app'.""" raw = compose.get("name") if isinstance(compose, dict) else None if not raw: return "app" - cleaned = _CHART_NAME_INVALID.sub("-", str(raw).lower()).strip("-") + cleaned = CHART_NAME_INVALID.sub("-", str(raw).lower()).strip("-") return cleaned[:63].rstrip("-") or "app" -def _render_chart( - manifests: dict[str, list[dict[str, Any]]], chart_name: str -) -> list[dict[str, str]]: - values: dict[str, Any] = {} - files: list[dict[str, str]] = [] - - workloads: dict[str, Any] = {} - for deployment in manifests.get("deployments", []): - name = deployment["metadata"]["name"] - container = deployment["spec"]["template"]["spec"]["containers"][0] - entry: dict[str, Any] = { - "image": container["image"], - "replicas": deployment["spec"]["replicas"], - } - if "resources" in container: - entry["resources"] = container["resources"] - workloads[name] = entry - files.append( - { - "path": f"templates/{name}-deployment.yaml", - "content": _templated_deployment(deployment, name), - } - ) - if workloads: - values["services"] = workloads - - storage: dict[str, Any] = {} - for pvc in manifests.get("persistent_volume_claims", []): - name = pvc["metadata"]["name"] - storage[name] = {"size": pvc["spec"]["resources"]["requests"]["storage"]} - files.append({"path": f"templates/{name}-pvc.yaml", "content": _templated_pvc(pvc, name)}) - if storage: - values["volumes"] = storage - - for service in manifests.get("services", []): - name = service["metadata"]["name"] - files.append( - { - "path": f"templates/{name}-service.yaml", - "content": _dump(_without_namespace(service)), - } - ) - - chart = { - "apiVersion": "v2", - "name": chart_name, - "description": "Generated by DevToolkit from a docker-compose file", - "type": "application", - "version": "0.1.0", - "appVersion": "0.1.0", - } - return [ - {"path": "Chart.yaml", "content": _dump(chart)}, - {"path": "values.yaml", "content": _dump(values)}, - *files, - ] - - -def _without_namespace(resource: dict[str, Any]) -> dict[str, Any]: +def without_namespace(resource: dict[str, Any]) -> dict[str, Any]: """Helm puts resources in the release namespace, so templates carry none.""" copy = dict(resource) copy["metadata"] = {k: v for k, v in resource["metadata"].items() if k != "namespace"} return copy -def _values_ref(section: str, name: str) -> str: - # Names can contain '-', which Go templates can't take after a dot, so use index. +def values_ref(section: str, name: str) -> str: + """A reference to the values of `name` in `section`. Names can contain '-', which Go + templates cannot take after a dot, so it uses index.""" return f'(index .Values.{section} "{name}")' -def _templated_deployment(deployment: dict[str, Any], name: str) -> str: - doc = _without_namespace(deployment) - spec = dict(doc["spec"]) - template = dict(spec["template"]) - pod = dict(template["spec"]) - container = dict(pod["containers"][0]) - - container["image"] = _SENTINEL.format(kind="image", name=name) - spec["replicas"] = _SENTINEL.format(kind="replicas", name=name) - has_resources = "resources" in container - if has_resources: - container["resources"] = _SENTINEL.format(kind="resources", name=name) - pod["containers"] = [container, *pod["containers"][1:]] - template["spec"] = pod - spec["template"] = template - doc["spec"] = spec - - text = _dump(doc) - ref = _values_ref("services", name) - text = text.replace(_SENTINEL.format(kind="image", name=name), f"{{{{ {ref}.image | quote }}}}") - text = text.replace(_SENTINEL.format(kind="replicas", name=name), f"{{{{ {ref}.replicas }}}}") - if has_resources: - # The sentinel sits on its own line as `resources: __...__`; replace the value with - # a toYaml block indented under the key. - text = re.sub( - r"^(\s*)resources: " + re.escape(_SENTINEL.format(kind="resources", name=name)) + "$", - lambda m: ( - f"{m.group(1)}resources:\n" - f"{m.group(1)} {{{{- toYaml {ref}.resources | nindent {len(m.group(1)) + 2} }}}}" - ), - text, - flags=re.M, +class ResourcesBlock: + """Swaps the `resources: ` line of a deployment template for a toYaml block + indented under the key.""" + + def __init__(self, ref: str) -> None: + """`ref`: the values reference of the service.""" + self.ref = ref + + def replace(self, match: re.Match[str]) -> str: + """The block for one matched line; group 1 is its indentation.""" + indent = match.group(1) + return ( + f"{indent}resources:\n" + f"{indent} {{{{- toYaml {self.ref}.resources | nindent {len(indent) + 2} }}}}" + ) + + +class HelmChart: + """A Helm chart for converted manifests: Chart.yaml, values.yaml with what people + change between environments, and one template per resource.""" + + def __init__(self, manifests: dict[str, list[dict[str, Any]]], chart_name: str) -> None: + """The manifests of a convert_compose_to_k8s() result and the chart name.""" + self.manifests = manifests + self.chart_name = chart_name + + def render(self) -> list[dict[str, str]]: + """Every file of the chart as {"path", "content"}.""" + values: dict[str, Any] = {} + files: list[dict[str, str]] = [] + + workloads: dict[str, Any] = {} + for deployment in self.manifests.get("deployments", []): + name = deployment["metadata"]["name"] + container = deployment["spec"]["template"]["spec"]["containers"][0] + entry: dict[str, Any] = { + "image": container["image"], + "replicas": deployment["spec"]["replicas"], + } + if "resources" in container: + entry["resources"] = container["resources"] + workloads[name] = entry + files.append( + { + "path": f"templates/{name}-deployment.yaml", + "content": self.deployment_template(deployment, name), + } + ) + if workloads: + values["services"] = workloads + + storage: dict[str, Any] = {} + for pvc in self.manifests.get("persistent_volume_claims", []): + name = pvc["metadata"]["name"] + storage[name] = {"size": pvc["spec"]["resources"]["requests"]["storage"]} + files.append( + {"path": f"templates/{name}-pvc.yaml", "content": self.pvc_template(pvc, name)} + ) + if storage: + values["volumes"] = storage + + for service in self.manifests.get("services", []): + name = service["metadata"]["name"] + files.append( + { + "path": f"templates/{name}-service.yaml", + "content": dump(without_namespace(service)), + } + ) + + chart = { + "apiVersion": "v2", + "name": self.chart_name, + "description": "Generated by DevToolkit from a docker-compose file", + "type": "application", + "version": "0.1.0", + "appVersion": "0.1.0", + } + return [ + {"path": "Chart.yaml", "content": dump(chart)}, + {"path": "values.yaml", "content": dump(values)}, + ] + files + + def deployment_template(self, deployment: dict[str, Any], name: str) -> str: + """A deployment with image, replicas and resources read from values.yaml.""" + doc = without_namespace(deployment) + spec = dict(doc["spec"]) + template = dict(spec["template"]) + pod = dict(template["spec"]) + container = dict(pod["containers"][0]) + + container["image"] = SENTINEL.format(kind="image", name=name) + spec["replicas"] = SENTINEL.format(kind="replicas", name=name) + has_resources = "resources" in container + if has_resources: + container["resources"] = SENTINEL.format(kind="resources", name=name) + pod["containers"] = [container] + pod["containers"][1:] + template["spec"] = pod + spec["template"] = template + doc["spec"] = spec + + text = dump(doc) + ref = values_ref("services", name) + text = text.replace( + SENTINEL.format(kind="image", name=name), f"{{{{ {ref}.image | quote }}}}" + ) + text = text.replace( + SENTINEL.format(kind="replicas", name=name), f"{{{{ {ref}.replicas }}}}" + ) + if has_resources: + # The sentinel sits on its own line as `resources: __...__`. + text = re.sub( + r"^(\s*)resources: " + + re.escape(SENTINEL.format(kind="resources", name=name)) + + "$", + ResourcesBlock(ref).replace, + text, + flags=re.M, + ) + return text + + def pvc_template(self, pvc: dict[str, Any], name: str) -> str: + """A PersistentVolumeClaim with its size read from values.yaml.""" + doc = without_namespace(pvc) + spec = dict(doc["spec"]) + resources = dict(spec["resources"]) + resources["requests"] = {"storage": SENTINEL.format(kind="storage", name=name)} + spec["resources"] = resources + doc["spec"] = spec + text = dump(doc) + return text.replace( + SENTINEL.format(kind="storage", name=name), + f"{{{{ {values_ref('volumes', name)}.size | quote }}}}", ) - return text - - -def _templated_pvc(pvc: dict[str, Any], name: str) -> str: - doc = _without_namespace(pvc) - spec = dict(doc["spec"]) - resources = dict(spec["resources"]) - resources["requests"] = {"storage": _SENTINEL.format(kind="storage", name=name)} - spec["resources"] = resources - doc["spec"] = spec - text = _dump(doc) - return text.replace( - _SENTINEL.format(kind="storage", name=name), - f"{{{{ {_values_ref('volumes', name)}.size | quote }}}}", - ) __all__ = ["OUTPUTS", "chart_name_from", "render_files", "to_k8s_name"] diff --git a/services/converter-api/converters/yaml_safety.py b/services/converter-api/converters/yaml_safety.py new file mode 100644 index 0000000..e6569df --- /dev/null +++ b/services/converter-api/converters/yaml_safety.py @@ -0,0 +1,154 @@ +"""Safe, bounded YAML loading shared by the compose and CloudFormation converters. + +Every loader here is a SafeLoader subclass, so YAML can only build the standard types +(mappings, lists, strings, numbers, booleans, null), never Python objects. The limits stop +oversized input, deep nesting and alias bombs before they cost real CPU time. +""" + +from __future__ import annotations + +from typing import Any + +import yaml + +# Upper bound on YAML values, both as written and after aliases are expanded. A real compose +# file has a few hundred; this stops oversized or "billion laughs" input from eating CPU. +MAX_NODES = 10_000 +# Real compose files nest lists and mappings fewer than 10 levels deep. +MAX_DEPTH = 100 + +# The C parser of libyaml ships in the PyYAML wheel and is 10-100x faster than the pure-Python +# one (50,000 nested brackets: ~3ms vs ~0.3s). Fall back if PyYAML was built without it. +FAST_LOADER = getattr(yaml, "CSafeLoader", yaml.SafeLoader) + +NULL_TAG = "tag:yaml.org,2002:null" +MERGE_TAG = "tag:yaml.org,2002:merge" + + +class YamlLimitError(ValueError): + """Raised when YAML input is too large or nested too deeply. + + `message` is written for the user and is safe to send back to them. + """ + + def __init__(self, message: str) -> None: + """Keep the user text as `message`.""" + super().__init__(message) + self.message = message + + +class SafeMergeLoader(FAST_LOADER): + """Safe loader whose `<<` merge keys cost linear, not exponential, time. + + PyYAML copies every merged key/value pair once per reference before de-duplicating, so + `a2: {<<: [*a1, *a1, ...]}` chained a few levels deep grows 9x per level (a 500-char + input can take minutes). Dropping duplicate keys after each merge keeps it linear. The + last occurrence of a key wins, which is the same result PyYAML gives. + """ + + def flatten_mapping(self, node: yaml.MappingNode) -> None: + """Merge the `<<` keys of `node`, then keep only the last value of each key.""" + super().flatten_mapping(node) + seen: set[tuple[str, str]] = set() + kept: list[tuple[yaml.Node, yaml.Node]] = [] + for key_node, value_node in reversed(node.value): + if isinstance(key_node, yaml.ScalarNode): + key = (key_node.tag, key_node.value) + if key in seen: + continue + seen.add(key) + kept.append((key_node, value_node)) + kept.reverse() + node.value = kept + + +class PlainScalarLoader(SafeMergeLoader): + """Loader that keeps plain scalars as strings, except null and `<<` merge keys. + + PyYAML follows YAML 1.1, where `on` means True, `0755` is octal 493 and an unquoted + `22:22` is the base-60 number 1342. Compose uses YAML 1.2, so those values must reach + the container unchanged. Keeping the text as it is gives the same result, and numeric + fields (ports, replicas, cpus) are converted explicitly by the caller. + """ + + +PlainScalarLoader.yaml_implicit_resolvers = { + first_char: [(tag, regexp) for tag, regexp in resolvers if tag in (NULL_TAG, MERGE_TAG)] + for first_char, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items() +} + + +def load_single(text: str, loader_class: type[yaml.SafeLoader]) -> Any: + """Build the single document in `text` with one of the safe loaders above. + + This is what yaml.load() does internally, spelled out so the loader is visibly a + SafeLoader subclass. + """ + loader = loader_class(text) + try: + return loader.get_single_data() + finally: + loader.dispose() + + +def load_yaml_documents(text: str) -> list[Any]: + """Build every document in a multi-document YAML string (separated by ---). + + Uses SafeMergeLoader: safe types only, and linear-time `<<` merges. Raises yaml.YAMLError + on syntax errors. + """ + loader = SafeMergeLoader(text) + try: + documents: list[Any] = [] + while loader.check_data(): + documents.append(loader.get_data()) + return documents + finally: + loader.dispose() + + +def check_yaml_limits(text: str, max_depth: int = MAX_DEPTH, max_nodes: int = MAX_NODES) -> None: + """Raise YamlLimitError if YAML nests deeper than `max_depth` or has over `max_nodes` + values. + + Building objects is the expensive part of loading YAML, and it recurses, so `[[[[...]]]]` + thousands deep or a 60 KB list of 30,000 items costs about a second of CPU. The parser's + event stream is flat and runs in C, so checking it first rejects both in milliseconds. + Aliases are counted once here; check_node_count() covers their expanded size. + + Raises yaml.YAMLError for syntax errors, so callers can report them as usual. + """ + depth = 0 + nodes = 0 + for event in yaml.parse(text, Loader=FAST_LOADER): + if isinstance(event, yaml.NodeEvent): + nodes += 1 + if nodes > max_nodes: + raise YamlLimitError(f"Input too large: more than {max_nodes} values") + if isinstance(event, yaml.CollectionStartEvent): + depth += 1 + if depth > max_depth: + raise YamlLimitError("Invalid YAML: nested too deeply") + elif isinstance(event, yaml.CollectionEndEvent): + depth -= 1 + + +def check_node_count(data: Any, limit: int = MAX_NODES) -> None: + """Raise YamlLimitError if `data` has more than `limit` nodes once aliases are expanded. + + Stops counting as soon as the limit is passed, so even a huge alias bomb is rejected fast. + """ + count = 0 + stack = [data] + while stack: + node = stack.pop() + count += 1 + if count > limit: + raise YamlLimitError( + f"Input too large: more than {limit} values after expanding YAML aliases" + ) + if isinstance(node, dict): + stack.extend(node.keys()) + stack.extend(node.values()) + elif isinstance(node, list): + stack.extend(node) diff --git a/services/converter-api/main.py b/services/converter-api/main.py index cc0c314..c31309c 100644 --- a/services/converter-api/main.py +++ b/services/converter-api/main.py @@ -4,29 +4,30 @@ import logging import os -from typing import Any, Literal +from typing import Any import yaml from fastapi import FastAPI from fastapi.responses import JSONResponse -from pydantic import BaseModel, Field +from converters.cfn.errors import CfnError +from converters.cfn.pipeline import convert_template from converters.compose_to_k8s import ( ComposeError, - check_yaml_limits, convert_compose_to_k8s, - load_yaml_documents, manifests_to_yaml, parse_compose, ) from converters.render import chart_name_from, render_files +from converters.yaml_safety import YamlLimitError, check_yaml_limits, load_yaml_documents +from schemas import CfnRequest, ConvertFilesRequest, ConvertRequest, ValidateRequest LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") def resolve_log_level(value: str | None) -> tuple[str, str | None]: """Return (level, warning). An unknown LOG_LEVEL falls back to INFO instead of crashing, - so a typo in the ConfigMap doesn't put every pod into CrashLoopBackOff.""" + so a typo in the ConfigMap does not put every pod into CrashLoopBackOff.""" level = (value or "info").strip().upper() if level in LOG_LEVELS: return level, None @@ -48,35 +49,18 @@ def configure_logging(value: str | None) -> str: LOG_LEVEL = configure_logging(os.getenv("LOG_LEVEL")) -# Large enough for any real compose file, small enough to stop someone posting megabytes of YAML. -MAX_INPUT_CHARS = 100_000 -# K8s namespace names are DNS-1123 labels. -NAMESPACE_PATTERN = r"^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$" - app = FastAPI( title="DevToolkit converter-api", - description="Convert docker-compose files into Kubernetes manifests.", + description=( + "Convert docker-compose files into Kubernetes manifests and CloudFormation, AWS SAM " + "and AWS CDK templates into Terraform." + ), version="1.0.0", ) -class ConvertRequest(BaseModel): - compose_yaml: str = Field(..., max_length=MAX_INPUT_CHARS, description="docker-compose YAML") - namespace: str = Field("default", pattern=NAMESPACE_PATTERN) - include_service: bool = True - - -class ConvertFilesRequest(ConvertRequest): - output: Literal["manifests", "helm"] = Field( - "manifests", description="'manifests': one YAML file per resource. 'helm': a Helm chart." - ) - - -class ValidateRequest(BaseModel): - yaml: str = Field(..., max_length=MAX_INPUT_CHARS) - - -def _error(exc: ComposeError, status_code: int = 400) -> JSONResponse: +def _error(exc: ComposeError | CfnError, status_code: int = 400) -> JSONResponse: + """The JSON error response for a rejected input, with its position when known.""" content: dict[str, Any] = {"success": False, "error": exc.message} if exc.line is not None: content["line"] = exc.line @@ -85,6 +69,7 @@ def _error(exc: ComposeError, status_code: int = 400) -> JSONResponse: def _convert(request: ConvertRequest) -> dict[str, Any]: + """Parse and convert the compose file of a request.""" compose = parse_compose(request.compose_yaml) return convert_compose_to_k8s(compose, request.namespace, request.include_service) @@ -141,6 +126,37 @@ def convert_compose_files(request: ConvertFilesRequest) -> dict[str, Any] | JSON return {"success": True, "output": request.output, "files": files, "notes": result["notes"]} +@app.post("/convert/cfn-to-terraform", response_model=None) +def convert_cfn(request: CfnRequest) -> dict[str, Any] | JSONResponse: + """Convert a CloudFormation, AWS SAM or AWS CDK (synthesized) template to Terraform files.""" + try: + result = convert_template( + request.template, + provider=request.provider, + layout=request.layout, + stack_name=request.stack_name, + include_imports=request.include_imports, + ) + except CfnError as exc: + logger.info("conversion rejected: %s", exc) + return _error(exc) + except (KeyError, TypeError, AttributeError, IndexError, ValueError): + # A template shape the converter does not expect is a bug to fix, but the user still + # gets an answer instead of a 500, which the web page would show as an outage. + logger.exception("cfn-to-terraform failed on an unexpected template shape") + return JSONResponse( + status_code=400, + content={ + "success": False, + "error": "This template has a structure the converter cannot handle yet. " + "Please open an issue with a small example.", + }, + ) + response: dict[str, Any] = {"success": True} + response.update(result) + return response + + @app.post("/validate/yaml") def validate_yaml(request: ValidateRequest) -> dict[str, Any]: """Check YAML syntax. Supports multi-document input (separated by ---).""" @@ -148,7 +164,7 @@ def validate_yaml(request: ValidateRequest) -> dict[str, Any]: check_yaml_limits(request.yaml) # Safe loader with linear-time `<<` merges (plain safe_load_all is exponential). documents = load_yaml_documents(request.yaml) - except ComposeError as exc: + except YamlLimitError as exc: return {"valid": False, "error": exc.message} except yaml.YAMLError as exc: # Only the parser's description of the input is returned, never the exception text. diff --git a/services/converter-api/schemas.py b/services/converter-api/schemas.py new file mode 100644 index 0000000..e6a925e --- /dev/null +++ b/services/converter-api/schemas.py @@ -0,0 +1,64 @@ +"""Request bodies of the converter-api endpoints, with the limits each field enforces.""" + +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel, Field + +from converters.cfn.constants import MAX_TEMPLATE_CHARS + +# Large enough for any real compose file, small enough to stop someone posting megabytes of YAML. +MAX_INPUT_CHARS = 100_000 +# K8s namespace names are DNS-1123 labels. +NAMESPACE_PATTERN = r"^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$" +# CloudFormation stack names: a letter, then letters, digits and '-', at most 128 characters. +STACK_NAME_PATTERN = r"^[A-Za-z][-A-Za-z0-9]{0,127}$" + + +class ConvertRequest(BaseModel): + """A docker-compose file to convert to Kubernetes manifests.""" + + compose_yaml: str = Field(..., max_length=MAX_INPUT_CHARS, description="docker-compose YAML") + namespace: str = Field("default", pattern=NAMESPACE_PATTERN) + include_service: bool = True + + +class ConvertFilesRequest(ConvertRequest): + """A docker-compose file to convert, and the kind of files to return.""" + + output: Literal["manifests", "helm"] = Field( + "manifests", description="'manifests': one YAML file per resource. 'helm': a Helm chart." + ) + + +class CfnRequest(BaseModel): + """A CloudFormation, AWS SAM or synthesized CDK template to convert to Terraform.""" + + template: str = Field( + ..., + max_length=MAX_TEMPLATE_CHARS, + description="CloudFormation, AWS SAM or `cdk synth` template, JSON or YAML", + ) + provider: Literal["aws", "awscc"] = Field( + "aws", + description="'aws': hand-written aws provider mappings, awscc for other types. " + "'awscc': every resource with the awscc provider.", + ) + layout: Literal["files", "single"] = Field( + "files", description="'files': versions.tf, variables.tf, main.tf... 'single': main.tf" + ) + stack_name: str | None = Field( + None, + pattern=STACK_NAME_PATTERN, + description="Default for var.stack_name, which replaces AWS::StackName", + ) + include_imports: bool = Field( + False, description="Also write imports.tf, to adopt resources the stack already created" + ) + + +class ValidateRequest(BaseModel): + """YAML text to check, one document or several separated by ---.""" + + yaml: str = Field(..., max_length=MAX_INPUT_CHARS) diff --git a/services/converter-api/tests/fixtures/cfn/apigateway.yaml b/services/converter-api/tests/fixtures/cfn/apigateway.yaml new file mode 100644 index 0000000..5c26fef --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/apigateway.yaml @@ -0,0 +1,233 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: API Gateway REST (v1) and HTTP (v2) APIs. +Parameters: + FunctionArn: + Type: String + Default: arn:aws:lambda:us-east-1:123456789012:function:orders + LogGroupArn: + Type: String + Default: arn:aws:logs:us-east-1:123456789012:log-group:api + Debug: + Type: String + Default: "false" +Conditions: + Debugging: !Equals [!Ref Debug, "true"] +Resources: + Api: + Type: AWS::ApiGateway::RestApi + Properties: + Name: orders-api + Description: Orders REST API + BinaryMediaTypes: [image/png] + MinimumCompressionSize: 1024 + EndpointConfiguration: + Types: [REGIONAL] + Tags: + - Key: team + Value: orders + OrdersResource: + Type: AWS::ApiGateway::Resource + Properties: + RestApiId: !Ref Api + ParentId: !GetAtt Api.RootResourceId + PathPart: orders + GetOrders: + Type: AWS::ApiGateway::Method + Properties: + RestApiId: !Ref Api + ResourceId: !Ref OrdersResource + HttpMethod: GET + AuthorizationType: NONE + ApiKeyRequired: false + RequestParameters: + method.request.querystring.limit: false + MethodResponses: + - StatusCode: 200 + ResponseModels: + application/json: Empty + - !If + - Debugging + - StatusCode: 500 + - !Ref AWS::NoValue + Integration: + Type: AWS_PROXY + IntegrationHttpMethod: POST + Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FunctionArn}/invocations" + TimeoutInMillis: 29000 + IntegrationResponses: + - StatusCode: 200 + SelectionPattern: "" + - !If + - Debugging + - StatusCode: 500 + SelectionPattern: "Error.*" + - !Ref AWS::NoValue + PostOrders: + Type: AWS::ApiGateway::Method + Properties: + RestApiId: !Ref Api + ResourceId: !Ref OrdersResource + HttpMethod: POST + Integration: + Type: MOCK + RequestTemplates: + application/json: '{"statusCode": 200}' + Deployment: + Type: AWS::ApiGateway::Deployment + DependsOn: [GetOrders, PostOrders] + Properties: + RestApiId: !Ref Api + Description: Initial deployment + Prod: + Type: AWS::ApiGateway::Stage + Properties: + RestApiId: !Ref Api + DeploymentId: !Ref Deployment + StageName: prod + Description: Production + TracingEnabled: true + Variables: + mode: live + AccessLogSetting: + DestinationArn: !Ref LogGroupArn + Format: "$context.requestId" + MethodSettings: + - ResourcePath: "/*" + HttpMethod: "*" + MetricsEnabled: true + LoggingLevel: INFO + ThrottlingBurstLimit: 100 + ThrottlingRateLimit: 50 + - ResourcePath: "/~1orders" + HttpMethod: GET + CachingEnabled: false + - ResourcePath: / + HttpMethod: GET + MetricsEnabled: true + - !If + - Debugging + - ResourcePath: "/*" + HttpMethod: POST + DataTraceEnabled: true + - !Ref AWS::NoValue + SpecApi: + Type: AWS::ApiGateway::RestApi + Properties: + Body: + openapi: "3.0.1" + info: + title: spec-api + version: "1.0" + paths: + /ping: + get: + x-amazon-apigateway-integration: + type: mock + requestTemplates: + application/json: '{"statusCode": 200}' + SpecDeployment: + Type: AWS::ApiGateway::Deployment + Properties: + RestApiId: !Ref SpecApi + StageName: v1 + StageDescription: + Description: Version 1 + TracingEnabled: true + HttpApi: + Type: AWS::ApiGatewayV2::Api + Properties: + Name: orders-http + ProtocolType: HTTP + Description: Orders HTTP API + CorsConfiguration: + AllowOrigins: ["https://example.com"] + AllowMethods: [GET, POST] + AllowHeaders: [authorization] + MaxAge: 600 + Tags: + team: orders + HttpIntegration: + Type: AWS::ApiGatewayV2::Integration + Properties: + ApiId: !Ref HttpApi + IntegrationType: AWS_PROXY + IntegrationUri: !Ref FunctionArn + PayloadFormatVersion: "2.0" + TimeoutInMillis: 10000 + Authorizer: + Type: AWS::ApiGatewayV2::Authorizer + Properties: + ApiId: !Ref HttpApi + Name: jwt + AuthorizerType: JWT + IdentitySource: [$request.header.Authorization] + JwtConfiguration: + Audience: [orders] + Issuer: https://auth.example.com/ + HttpRoute: + Type: AWS::ApiGatewayV2::Route + Properties: + ApiId: !Ref HttpApi + RouteKey: GET /orders + Target: !Sub "integrations/${HttpIntegration}" + AuthorizationType: JWT + AuthorizerId: !Ref Authorizer + AuthorizationScopes: [orders.read] + HttpStage: + Type: AWS::ApiGatewayV2::Stage + Properties: + ApiId: !Ref HttpApi + StageName: $default + AutoDeploy: true + DefaultRouteSettings: + DetailedMetricsEnabled: true + ThrottlingBurstLimit: 20 + ThrottlingRateLimit: 10 + RouteSettings: + GET /orders: + ThrottlingBurstLimit: 5 + GET /debug: !If + - Debugging + - ThrottlingBurstLimit: 1 + - !Ref AWS::NoValue + AccessLogSettings: + DestinationArn: !Ref LogGroupArn + Format: "$context.requestId" + StageVariables: + mode: live + SocketApi: + Type: AWS::ApiGatewayV2::Api + Properties: + Name: chat + ProtocolType: WEBSOCKET + RouteSelectionExpression: $request.body.action + SocketRoute: + Type: AWS::ApiGatewayV2::Route + Properties: + ApiId: !Ref SocketApi + RouteKey: $connect + RequestParameters: + route.request.header.Auth: + Required: true + route.request.querystring.trace: !If + - Debugging + - Required: false + - !Ref AWS::NoValue + SpecHttpApi: + Type: AWS::ApiGatewayV2::Api + Properties: + Body: + openapi: "3.0.1" + info: + title: spec-http + version: "1.0" + paths: {} +Outputs: + RestApiId: + Value: !Ref Api + StageName: + Value: !Ref Prod + HttpEndpoint: + Value: !GetAtt HttpApi.ApiEndpoint + HttpStageName: + Value: !Ref HttpStage diff --git a/services/converter-api/tests/fixtures/cfn/cdk.json b/services/converter-api/tests/fixtures/cfn/cdk.json new file mode 100644 index 0000000..4cc675b --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/cdk.json @@ -0,0 +1,228 @@ +{ + "Resources": { + "SiteBucket397A1860": { + "Type": "AWS::S3::Bucket", + "Properties": { + "BucketEncryption": { + "ServerSideEncryptionConfiguration": [ + {"ServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}} + ] + }, + "PublicAccessBlockConfiguration": { + "BlockPublicAcls": true, + "BlockPublicPolicy": true, + "IgnorePublicAcls": true, + "RestrictPublicBuckets": true + }, + "Tags": [{"Key": "aws-cdk:auto-delete-objects", "Value": "true"}] + }, + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete", + "Metadata": {"aws:cdk:path": "WebStack/SiteBucket/Resource"} + }, + "SiteBucketPolicy3AC1D0F8": { + "Type": "AWS::S3::BucketPolicy", + "Properties": { + "Bucket": {"Ref": "SiteBucket397A1860"}, + "PolicyDocument": { + "Statement": [ + { + "Action": "s3:*", + "Condition": {"Bool": {"aws:SecureTransport": "false"}}, + "Effect": "Deny", + "Principal": {"AWS": "*"}, + "Resource": [ + {"Fn::GetAtt": ["SiteBucket397A1860", "Arn"]}, + {"Fn::Join": ["", [{"Fn::GetAtt": ["SiteBucket397A1860", "Arn"]}, "/*"]]} + ] + }, + { + "Action": ["s3:DeleteObject*", "s3:GetBucket*", "s3:List*", "s3:PutBucketPolicy"], + "Effect": "Allow", + "Principal": { + "AWS": {"Fn::GetAtt": ["CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092", "Arn"]} + }, + "Resource": [ + {"Fn::GetAtt": ["SiteBucket397A1860", "Arn"]}, + {"Fn::Join": ["", [{"Fn::GetAtt": ["SiteBucket397A1860", "Arn"]}, "/*"]]} + ] + } + ], + "Version": "2012-10-17" + } + }, + "Metadata": {"aws:cdk:path": "WebStack/SiteBucket/Policy/Resource"} + }, + "SiteBucketAutoDeleteObjectsCustomResource6C0C6E1D": { + "Type": "Custom::S3AutoDeleteObjects", + "Properties": { + "ServiceToken": {"Fn::GetAtt": ["CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F", "Arn"]}, + "BucketName": {"Ref": "SiteBucket397A1860"} + }, + "DependsOn": ["SiteBucketPolicy3AC1D0F8"], + "UpdateReplacePolicy": "Delete", + "DeletionPolicy": "Delete", + "Metadata": {"aws:cdk:path": "WebStack/SiteBucket/AutoDeleteObjectsCustomResource/Default"} + }, + "CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Version": "2012-10-17", + "Statement": [{"Action": "sts:AssumeRole", "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}}] + }, + "ManagedPolicyArns": [ + {"Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"} + ] + }, + "Metadata": {"aws:cdk:path": "WebStack/Custom::S3AutoDeleteObjectsCustomResourceProvider/Role"} + }, + "CustomS3AutoDeleteObjectsCustomResourceProviderHandler9D90184F": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "S3Bucket": {"Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}"}, + "S3Key": "faa95a81ae7d7373f3e1f242268f904eb748d8d0fdd306e8a6fe515a1905a7d6.zip" + }, + "Timeout": 900, + "MemorySize": 128, + "Handler": "index.handler", + "Role": {"Fn::GetAtt": ["CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092", "Arn"]}, + "Runtime": "nodejs22.x" + }, + "DependsOn": ["CustomS3AutoDeleteObjectsCustomResourceProviderRole3B1BD092"], + "Metadata": { + "aws:cdk:path": "WebStack/Custom::S3AutoDeleteObjectsCustomResourceProvider/Handler", + "aws:asset:path": "asset.faa95a81ae7d7373f3e1f242268f904eb748d8d0fdd306e8a6fe515a1905a7d6", + "aws:asset:property": "Code" + } + }, + "ApiHandlerServiceRoleBE1A9EF3": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [{"Action": "sts:AssumeRole", "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}}], + "Version": "2012-10-17" + }, + "ManagedPolicyArns": [ + {"Fn::Join": ["", ["arn:", {"Ref": "AWS::Partition"}, ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]]} + ] + }, + "Metadata": {"aws:cdk:path": "WebStack/ApiHandler/ServiceRole/Resource"} + }, + "ApiHandlerServiceRoleDefaultPolicy6A1A4F2B": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyDocument": { + "Statement": [ + { + "Action": ["s3:GetObject*", "s3:GetBucket*", "s3:List*"], + "Effect": "Allow", + "Resource": [ + {"Fn::GetAtt": ["SiteBucket397A1860", "Arn"]}, + {"Fn::Join": ["", [{"Fn::GetAtt": ["SiteBucket397A1860", "Arn"]}, "/*"]]} + ] + } + ], + "Version": "2012-10-17" + }, + "PolicyName": "ApiHandlerServiceRoleDefaultPolicy6A1A4F2B", + "Roles": [{"Ref": "ApiHandlerServiceRoleBE1A9EF3"}] + }, + "Metadata": {"aws:cdk:path": "WebStack/ApiHandler/ServiceRole/DefaultPolicy/Resource"} + }, + "ApiHandler5E7490E8": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "S3Bucket": {"Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}"}, + "S3Key": "3b1f6f1e6d8d0c1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192.zip" + }, + "Environment": {"Variables": {"BUCKET": {"Ref": "SiteBucket397A1860"}}}, + "Handler": "index.handler", + "MemorySize": 256, + "Role": {"Fn::GetAtt": ["ApiHandlerServiceRoleBE1A9EF3", "Arn"]}, + "Runtime": "python3.13" + }, + "DependsOn": ["ApiHandlerServiceRoleDefaultPolicy6A1A4F2B", "ApiHandlerServiceRoleBE1A9EF3"], + "Metadata": { + "aws:cdk:path": "WebStack/ApiHandler/Resource", + "aws:asset:path": "asset.3b1f6f1e6d8d0c1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192", + "aws:asset:is-bundled": false, + "aws:asset:property": "Code" + } + }, + "ApiHandlerLogRetention9F6A9B6C": { + "Type": "Custom::LogRetention", + "Properties": { + "ServiceToken": {"Fn::GetAtt": ["LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8aFD4BFC8A", "Arn"]}, + "LogGroupName": {"Fn::Join": ["", ["/aws/lambda/", {"Ref": "ApiHandler5E7490E8"}]]}, + "RetentionInDays": 14 + }, + "Metadata": {"aws:cdk:path": "WebStack/ApiHandler/LogRetention/Resource"} + }, + "LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8aServiceRole9741ECFB": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [{"Action": "sts:AssumeRole", "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}}], + "Version": "2012-10-17" + } + }, + "Metadata": {"aws:cdk:path": "WebStack/LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8a/ServiceRole/Resource"} + }, + "LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8aFD4BFC8A": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs22.x", + "Timeout": 900, + "Code": { + "S3Bucket": {"Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}"}, + "S3Key": "4e26bf2d0a26f2097fb2b261f22bb51e3f6b4b52635777b1e54edbd8e2d58c35.zip" + }, + "Role": {"Fn::GetAtt": ["LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8aServiceRole9741ECFB", "Arn"]} + }, + "Metadata": { + "aws:cdk:path": "WebStack/LogRetentionaae0aa3c5b4d4f87b02d85b201efdd8a/Resource", + "aws:asset:path": "asset.4e26bf2d0a26f2097fb2b261f22bb51e3f6b4b52635777b1e54edbd8e2d58c35", + "aws:asset:property": "Code" + } + }, + "CDKMetadata": { + "Type": "AWS::CDK::Metadata", + "Properties": {"Analytics": "v2:deflate64:H4sIAAAAAAAA/zPSMzA0"}, + "Metadata": {"aws:cdk:path": "WebStack/CDKMetadata/Default"}, + "Condition": "CDKMetadataAvailable" + } + }, + "Outputs": { + "BucketName": {"Value": {"Ref": "SiteBucket397A1860"}}, + "HandlerArn": {"Value": {"Fn::GetAtt": ["ApiHandler5E7490E8", "Arn"]}} + }, + "Conditions": { + "CDKMetadataAvailable": { + "Fn::Or": [ + {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, + {"Fn::Equals": [{"Ref": "AWS::Region"}, "eu-west-1"]} + ] + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version", + "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [ + { + "Assert": {"Fn::Not": [{"Fn::Contains": [["1", "2", "3", "4", "5"], {"Ref": "BootstrapVersion"}]}]}, + "AssertDescription": "CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI." + } + ] + } + } +} diff --git a/services/converter-api/tests/fixtures/cfn/compute.yaml b/services/converter-api/tests/fixtures/cfn/compute.yaml new file mode 100644 index 0000000..35d698c --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/compute.yaml @@ -0,0 +1,435 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Lambda, EC2 and ECS resources converted by hand-written aws mappings. +Parameters: + SubnetId: + Type: AWS::EC2::Subnet::Id + Default: subnet-0123456789abcdef0 + SecurityGroupId: + Type: AWS::EC2::SecurityGroup::Id + Default: sg-0123456789abcdef0 + RoleArn: + Type: String + Default: arn:aws:iam::123456789012:role/app + ImageId: + Type: AWS::EC2::Image::Id + Default: ami-0123456789abcdef0 + UseVpc: + Type: String + Default: "false" +Conditions: + InVpc: !Equals [!Ref UseVpc, "true"] +Resources: + Handler: + Type: AWS::Lambda::Function + Properties: + FunctionName: orders-handler + Description: Handles orders + Runtime: python3.12 + Handler: app.handler + Role: !Ref RoleArn + MemorySize: "256" + Timeout: 30 + ReservedConcurrentExecutions: 5 + Architectures: [arm64] + Layers: [!Ref Layer] + Code: + ZipFile: | + def handler(event, context): + return {"ok": True} + Environment: + Variables: + TABLE_NAME: orders + STAGE: !Ref AWS::Region + VpcConfig: !If + - InVpc + - SubnetIds: [!Ref SubnetId] + SecurityGroupIds: [!Ref SecurityGroupId] + - !Ref AWS::NoValue + TracingConfig: + Mode: Active + DeadLetterConfig: + TargetArn: arn:aws:sqs:us-east-1:123456789012:dlq + EphemeralStorage: + Size: 1024 + LoggingConfig: + ApplicationLogLevel: INFO + SystemLogLevel: WARN + LogFormat: JSON + Tags: + - Key: team + Value: orders + NodeHandler: + Type: AWS::Lambda::Function + Properties: + Runtime: nodejs20.x + Handler: index.handler + Role: !Ref RoleArn + Code: + S3Bucket: my-artifacts + S3Key: node/handler.zip + S3ObjectVersion: "3" + LoggingConfig: + LogGroup: /custom/node + SnapStart: + ApplyOn: None + ImageHandler: + Type: AWS::Lambda::Function + Properties: + FunctionName: image-handler + Role: !Ref RoleArn + Code: + ImageUri: 123456789012.dkr.ecr.us-east-1.amazonaws.com/app:1.0 + ImageConfig: + Command: [app.handler] + EntryPoint: [/lambda-entrypoint.sh] + WorkingDirectory: /var/task + Layer: + Type: AWS::Lambda::LayerVersion + Properties: + LayerName: shared-libs + Description: Shared libraries + LicenseInfo: MIT + CompatibleRuntimes: [python3.12] + CompatibleArchitectures: [arm64] + Content: + S3Bucket: my-artifacts + S3Key: layers/shared.zip + Permission: + Type: AWS::Lambda::Permission + Properties: + Action: lambda:InvokeFunction + FunctionName: !Ref Handler + Principal: s3.amazonaws.com + SourceArn: arn:aws:s3:::uploads + SourceAccount: !Ref AWS::AccountId + Queue: + Type: AWS::SQS::Queue + Mapping: + Type: AWS::Lambda::EventSourceMapping + Properties: + FunctionName: !GetAtt Handler.Arn + EventSourceArn: !GetAtt Queue.Arn + BatchSize: 10 + Enabled: true + MaximumBatchingWindowInSeconds: 5 + FunctionResponseTypes: [ReportBatchItemFailures] + FilterCriteria: + Filters: + - Pattern: '{"body": {"type": ["order"]}}' + ScalingConfig: + MaximumConcurrency: 4 + StreamMapping: + Type: AWS::Lambda::EventSourceMapping + Properties: + FunctionName: !Ref NodeHandler + EventSourceArn: arn:aws:kinesis:us-east-1:123456789012:stream/events + StartingPosition: AT_TIMESTAMP + StartingPositionTimestamp: 1700000000 + BisectBatchOnFunctionError: true + MaximumRetryAttempts: 2 + MaximumRecordAgeInSeconds: 3600 + ParallelizationFactor: 2 + TumblingWindowInSeconds: 60 + DestinationConfig: + OnFailure: + Destination: !GetAtt Queue.Arn + Url: + Type: AWS::Lambda::Url + Properties: + TargetFunctionArn: !GetAtt Handler.Arn + AuthType: NONE + InvokeMode: BUFFERED + Cors: + AllowCredentials: true + AllowOrigins: ["https://example.com"] + AllowMethods: [GET] + AllowHeaders: [content-type] + ExposeHeaders: [x-request-id] + MaxAge: 300 + Version: + Type: AWS::Lambda::Version + Properties: + FunctionName: !Ref Handler + Description: v1 + Alias: + Type: AWS::Lambda::Alias + Properties: + Name: live + Description: Live traffic + FunctionName: !Ref Handler + FunctionVersion: !GetAtt Version.Version + RoutingConfig: + AdditionalVersionWeights: + - FunctionVersion: "1" + FunctionWeight: 0.1 + ProvisionedConcurrencyConfig: + ProvisionedConcurrentExecutions: 2 + CanaryAlias: + Type: AWS::Lambda::Alias + Properties: + Name: canary + FunctionName: !Ref Handler + FunctionVersion: !GetAtt Version.Version + RoutingConfig: !If + - InVpc + - AdditionalVersionWeights: + - FunctionVersion: "1" + FunctionWeight: 0.5 + - !Ref AWS::NoValue + ProvisionedConcurrencyConfig: !If + - InVpc + - ProvisionedConcurrentExecutions: 1 + - !Ref AWS::NoValue + Server: + Type: AWS::EC2::Instance + Properties: + ImageId: !Ref ImageId + InstanceType: t3.micro + KeyName: ops + SubnetId: !Ref SubnetId + SecurityGroupIds: [!Ref SecurityGroupId] + IamInstanceProfile: app-profile + Monitoring: true + EbsOptimized: "true" + CreditSpecification: + CPUCredits: standard + UserData: + Fn::Base64: !Sub | + #!/bin/bash + echo "region ${AWS::Region}" > /etc/motd + BlockDeviceMappings: + - DeviceName: /dev/xvda + Ebs: + VolumeSize: 20 + VolumeType: gp3 + Encrypted: true + DeleteOnTermination: true + - DeviceName: /dev/sdf + Ebs: + VolumeSize: 100 + VolumeType: gp3 + - DeviceName: /dev/sdb + VirtualName: ephemeral0 + - !If + - InVpc + - DeviceName: /dev/sdg + Ebs: + VolumeSize: 10 + - !Ref AWS::NoValue + Tags: + - Key: Name + Value: app-server + Bastion: + Type: AWS::EC2::Instance + Properties: + ImageId: !Ref ImageId + InstanceType: t3.nano + UserData: IyEvYmluL2Jhc2gK + NetworkInterfaces: + - DeviceIndex: "0" + AssociatePublicIpAddress: true + SubnetId: !Ref SubnetId + GroupSet: [!Ref SecurityGroupId] + DeleteOnTermination: true + Template: + Type: AWS::EC2::LaunchTemplate + Properties: + LaunchTemplateName: app-template + VersionDescription: Initial + TagSpecifications: + - ResourceType: launch-template + Tags: + - Key: team + Value: platform + LaunchTemplateData: + ImageId: !Ref ImageId + InstanceType: t3.small + KeyName: ops + SecurityGroupIds: [!Ref SecurityGroupId] + UserData: !Base64 "#!/bin/bash\necho hello" + IamInstanceProfile: + Name: app-profile + MetadataOptions: + HttpTokens: required + HttpPutResponseHopLimit: 2 + Monitoring: + Enabled: true + BlockDeviceMappings: + - DeviceName: /dev/xvda + Ebs: + VolumeSize: 30 + VolumeType: gp3 + Encrypted: true + - DeviceName: /dev/sdb + NoDevice: "" + NetworkInterfaces: + - DeviceIndex: 0 + AssociatePublicIpAddress: false + SubnetId: !Ref SubnetId + Groups: [!Ref SecurityGroupId] + TagSpecifications: + - ResourceType: instance + Tags: + - Key: Name + Value: from-template + Cluster: + Type: AWS::ECS::Cluster + Properties: + ClusterName: apps + ClusterSettings: + - Name: containerInsights + Value: enabled + CapacityProviders: [FARGATE, FARGATE_SPOT] + DefaultCapacityProviderStrategy: + - CapacityProvider: FARGATE + Weight: 1 + Base: 1 + Configuration: + ExecuteCommandConfiguration: + Logging: OVERRIDE + LogConfiguration: + CloudWatchLogGroupName: /ecs/exec + CloudWatchEncryptionEnabled: true + Tags: + - Key: team + Value: platform + TaskDefinition: + Type: AWS::ECS::TaskDefinition + Properties: + Family: web + Cpu: "256" + Memory: "512" + NetworkMode: awsvpc + RequiresCompatibilities: [FARGATE] + ExecutionRoleArn: !Ref RoleArn + TaskRoleArn: !Ref RoleArn + RuntimePlatform: + CpuArchitecture: ARM64 + OperatingSystemFamily: LINUX + EphemeralStorage: + SizeInGiB: 30 + ContainerDefinitions: + - Name: web + Image: nginx:1.27 + Essential: "true" + Cpu: "128" + PortMappings: + - ContainerPort: 80 + Protocol: tcp + Environment: + - Name: REGION + Value: !Ref AWS::Region + - Name: PORT + Value: 8080 + - Name: DEBUG + Value: false + LinuxParameters: + Tmpfs: + - ContainerPath: /tmp + Size: "64" + DockerLabels: + com.example.Team: platform + LogConfiguration: + LogDriver: awslogs + Options: + awslogs-group: /ecs/web + awslogs-region: !Ref AWS::Region + awslogs-stream-prefix: web + MountPoints: + - SourceVolume: data + ContainerPath: /data + ReadOnly: false + HealthCheck: + Command: [CMD-SHELL, "curl -f http://localhost/ || exit 1"] + Interval: 30 + Retries: 3 + - !If + - InVpc + - Name: sidecar + Image: busybox:1.36 + Essential: "false" + Memory: "64" + - !Ref AWS::NoValue + Volumes: + - Name: data + EFSVolumeConfiguration: + FilesystemId: fs-12345678 + TransitEncryption: ENABLED + AuthorizationConfig: + IAM: ENABLED + - Name: scratch + - Name: logs + Host: !If + - InVpc + - SourcePath: /var/log + - !Ref AWS::NoValue + Tags: + - Key: app + Value: web + Service: + Type: AWS::ECS::Service + Properties: + ServiceName: web + Cluster: !Ref Cluster + TaskDefinition: !Ref TaskDefinition + DesiredCount: 2 + LaunchType: FARGATE + PlatformVersion: LATEST + EnableExecuteCommand: true + PropagateTags: SERVICE + HealthCheckGracePeriodSeconds: 60 + DeploymentConfiguration: + MaximumPercent: 200 + MinimumHealthyPercent: 50 + DeploymentCircuitBreaker: + Enable: true + Rollback: true + NetworkConfiguration: + AwsvpcConfiguration: + AssignPublicIp: DISABLED + Subnets: [!Ref SubnetId] + SecurityGroups: [!Ref SecurityGroupId] + LoadBalancers: + - ContainerName: web + ContainerPort: 80 + TargetGroupArn: arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web/abc + DeploymentController: + Type: ECS + Tags: + - Key: app + Value: web + Worker: + Type: AWS::ECS::Service + Properties: + ServiceName: worker + Cluster: !Ref Cluster + TaskDefinition: !Ref TaskDefinition + LaunchType: FARGATE + NetworkConfiguration: + AwsvpcConfiguration: + Subnets: [!Ref SubnetId] + Agent: + Type: AWS::ECS::Service + Properties: + ServiceName: agent + Cluster: !Ref Cluster + TaskDefinition: !Ref TaskDefinition + LaunchType: EC2 + SchedulingStrategy: DAEMON +Outputs: + HandlerArn: + Value: !GetAtt Handler.Arn + HandlerName: + Value: !Ref Handler + FunctionUrl: + Value: !GetAtt Url.FunctionUrl + FunctionUrlRef: + Value: !Ref Url + Version: + Value: !GetAtt Version.Version + ServerIp: + Value: !GetAtt Server.PublicIp + TemplateVersion: + Value: !GetAtt Template.LatestVersionNumber + ServiceName: + Value: !GetAtt Service.Name diff --git a/services/converter-api/tests/fixtures/cfn/data.yaml b/services/converter-api/tests/fixtures/cfn/data.yaml new file mode 100644 index 0000000..0292868 --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/data.yaml @@ -0,0 +1,186 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Databases, keys, secrets and parameters +Parameters: + SubnetIds: + Type: List + Default: subnet-11111111,subnet-22222222 + SecurityGroupId: + Type: AWS::EC2::SecurityGroup::Id + Default: sg-12345678 + DbPassword: + Type: String + NoEcho: true + Default: change-me-please +Resources: + DataKey: + Type: AWS::KMS::Key + Properties: + Description: Data encryption key + EnableKeyRotation: true + Enabled: true + KeySpec: SYMMETRIC_DEFAULT + KeyUsage: ENCRYPT_DECRYPT + MultiRegion: false + PendingWindowInDays: 7 + RotationPeriodInDays: 365 + KeyPolicy: + Version: "2012-10-17" + Statement: + - Sid: Root + Effect: Allow + Principal: + AWS: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:root + Action: kms:* + Resource: "*" + Tags: + - Key: app + Value: shop + DataKeyAlias: + Type: AWS::KMS::Alias + Properties: + AliasName: alias/shop-data + TargetKeyId: !Ref DataKey + DbSubnets: + Type: AWS::RDS::DBSubnetGroup + Properties: + DBSubnetGroupName: shop-db + DBSubnetGroupDescription: Database subnets + SubnetIds: !Ref SubnetIds + Tags: + - Key: app + Value: shop + DbParams: + Type: AWS::RDS::DBParameterGroup + Properties: + DBParameterGroupName: Shop-Postgres + Description: Postgres settings + Family: postgres16 + Parameters: + log_min_duration_statement: 500 + rds.force_ssl: "1" + log_connections: true + Tags: + - Key: app + Value: shop + Database: + Type: AWS::RDS::DBInstance + Properties: + DBInstanceIdentifier: shop-db + Engine: postgres + EngineVersion: "16.4" + DBInstanceClass: db.t4g.micro + AllocatedStorage: "20" + MaxAllocatedStorage: 100 + StorageType: gp3 + StorageEncrypted: true + KmsKeyId: !GetAtt DataKey.Arn + MasterUsername: shop + ManageMasterUserPassword: true + MasterUserSecret: + KmsKeyId: !Ref DataKey + DBName: shop + Port: "5432" + MultiAZ: false + PubliclyAccessible: false + VPCSecurityGroups: + - !Ref SecurityGroupId + DBSubnetGroupName: !Ref DbSubnets + DBParameterGroupName: !Ref DbParams + BackupRetentionPeriod: 7 + PreferredBackupWindow: 03:00-04:00 + PreferredMaintenanceWindow: sun:05:00-sun:06:00 + DeletionProtection: true + AutoMinorVersionUpgrade: true + CopyTagsToSnapshot: true + EnableIAMDatabaseAuthentication: true + EnablePerformanceInsights: true + PerformanceInsightsRetentionPeriod: 7 + EnableCloudwatchLogsExports: [postgresql] + Tags: + - Key: app + Value: shop + ScratchDb: + Type: AWS::RDS::DBInstance + DeletionPolicy: Delete + Properties: + Engine: mysql + DBInstanceClass: db.t4g.micro + AllocatedStorage: 20 + MasterUsername: admin + MasterUserPassword: !Ref DbPassword + ApplyImmediately: false + Cluster: + Type: AWS::RDS::DBCluster + DeletionPolicy: Snapshot + Properties: + DBClusterIdentifier: Shop-Cluster + Engine: aurora-postgresql + EngineVersion: "16.4" + DatabaseName: shop + MasterUsername: shop + ManageMasterUserPassword: true + Port: 5432 + DBSubnetGroupName: !Ref DbSubnets + VpcSecurityGroupIds: [!Ref SecurityGroupId] + BackupRetentionPeriod: 7 + StorageEncrypted: true + KmsKeyId: !GetAtt DataKey.Arn + DeletionProtection: true + EnableHttpEndpoint: true + ServerlessV2ScalingConfiguration: + MinCapacity: 0.5 + MaxCapacity: 4 + Tags: + - Key: app + Value: shop + ClusterWriter: + Type: AWS::RDS::DBInstance + Properties: + DBInstanceIdentifier: Shop-Writer + DBClusterIdentifier: !Ref Cluster + Engine: aurora-postgresql + DBInstanceClass: db.serverless + PromotionTier: 0 + EnablePerformanceInsights: true + ApiKey: + Type: AWS::SecretsManager::Secret + Properties: + Name: shop/api-key + Description: Third-party API key + KmsKeyId: !Ref DataKey + SecretString: '{"key": "replace-me"}' + ReplicaRegions: + - Region: eu-west-1 + Tags: + - Key: app + Value: shop + Endpoint: + Type: AWS::SSM::Parameter + Properties: + Name: /shop/db/endpoint + Type: String + Value: !GetAtt Database.Endpoint.Address + Description: Database endpoint + Tier: Standard + DataType: text + Tags: + app: shop + Hosts: + Type: AWS::SSM::Parameter + Properties: + Type: StringList + Value: a,b + AllowedPattern: "^[a-z,]+$" +Outputs: + DbAddress: + Value: !GetAtt Database.Endpoint.Address + DbPort: + Value: !GetAtt Database.Endpoint.Port + DbSecret: + Value: !GetAtt Database.MasterUserSecret.SecretArn + ClusterEndpoint: + Value: !GetAtt Cluster.Endpoint.Address + KeyArn: + Value: !GetAtt DataKey.Arn + SecretArn: + Value: !Ref ApiKey diff --git a/services/converter-api/tests/fixtures/cfn/iam.yaml b/services/converter-api/tests/fixtures/cfn/iam.yaml new file mode 100644 index 0000000..0625ac9 --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/iam.yaml @@ -0,0 +1,119 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: IAM roles, policies, users and groups +Parameters: + Environment: + Type: String + Default: dev +Conditions: + IsProd: !Equals [!Ref Environment, prod] +Resources: + AppRole: + Type: AWS::IAM::Role + Properties: + RoleName: app-role + Description: Role for the app + Path: /service/ + MaxSessionDuration: 7200 + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + ManagedPolicyArns: + - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole + - !Sub arn:${AWS::Partition}:iam::aws:policy/AWSXRayDaemonWriteAccess + - !Ref ReadPolicy + - !If [IsProd, !Ref AWS::NoValue, arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess] + Policies: + - PolicyName: read-logs + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: [logs:GetLogEvents] + Resource: !Sub arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:* + Tags: + - Key: team + Value: platform + ReadPolicy: + Type: AWS::IAM::ManagedPolicy + Properties: + ManagedPolicyName: read-only-s3 + Description: Read S3 + Path: / + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: s3:GetObject + Resource: "*" + Groups: + - !Ref Developers + - !If [IsProd, !Ref AWS::NoValue, !Ref Developers] + ExtraPolicy: + Type: AWS::IAM::Policy + Properties: + PolicyName: extra + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: sqs:SendMessage + Resource: "*" + Roles: + - !If [IsProd, !Ref AppRole, !Ref AWS::NoValue] + Users: + - !Ref Deployer + Profile: + Type: AWS::IAM::InstanceProfile + Properties: + InstanceProfileName: app-profile + Path: / + Roles: + - !Ref AppRole + Deployer: + Type: AWS::IAM::User + Properties: + UserName: deployer + Path: / + Groups: + - !Ref Developers + ManagedPolicyArns: + - arn:aws:iam::aws:policy/ReadOnlyAccess + Policies: + - PolicyName: deploy + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: cloudformation:* + Resource: "*" + Tags: + - Key: team + Value: platform + Developers: + Type: AWS::IAM::Group + Properties: + GroupName: developers + Path: / + ManagedPolicyArns: + - arn:aws:iam::aws:policy/ReadOnlyAccess + Policies: + - PolicyName: describe + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: ec2:Describe* + Resource: "*" +Outputs: + RoleArn: + Value: !GetAtt AppRole.Arn + RoleId: + Value: !GetAtt AppRole.RoleId + PolicyArn: + Value: !Ref ReadPolicy + ProfileArn: + Value: !GetAtt Profile.Arn diff --git a/services/converter-api/tests/fixtures/cfn/messaging.yaml b/services/converter-api/tests/fixtures/cfn/messaging.yaml new file mode 100644 index 0000000..1d78e99 --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/messaging.yaml @@ -0,0 +1,259 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Queues, topics, event rules, streams and a state machine +Parameters: + Environment: + Type: String + Default: dev +Conditions: + IsProd: !Equals [!Ref Environment, prod] +Resources: + DeadLetters: + Type: AWS::SQS::Queue + Properties: + QueueName: orders-dlq.fifo + FifoQueue: true + ContentBasedDeduplication: true + DeduplicationScope: messageGroup + FifoThroughputLimit: perMessageGroupId + MessageRetentionPeriod: 1209600 + RedriveAllowPolicy: + redrivePermission: allowAll + Orders: + Type: AWS::SQS::Queue + Properties: + QueueName: orders.fifo + FifoQueue: "true" + VisibilityTimeout: "60" + DelaySeconds: 0 + MaximumMessageSize: 262144 + ReceiveMessageWaitTimeSeconds: 20 + KmsMasterKeyId: alias/aws/sqs + KmsDataKeyReusePeriodSeconds: 300 + RedrivePolicy: + deadLetterTargetArn: !GetAtt DeadLetters.Arn + maxReceiveCount: 5 + Tags: + - Key: app + Value: shop + Plain: + Type: AWS::SQS::Queue + Properties: + SqsManagedSseEnabled: true + OrdersPolicy: + Type: AWS::SQS::QueuePolicy + Properties: + Queues: + - !Ref Orders + - !If [IsProd, !Ref Plain, !Ref AWS::NoValue] + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: sns.amazonaws.com + Action: sqs:SendMessage + Resource: !GetAtt Orders.Arn + Alerts: + Type: AWS::SNS::Topic + Properties: + TopicName: alerts + DisplayName: Alerts + KmsMasterKeyId: alias/aws/sns + SignatureVersion: "2" + TracingConfig: Active + DeliveryPolicy: + http: + defaultHealthyRetryPolicy: + numRetries: 3 + Subscription: + - Protocol: email + Endpoint: ops@example.com + - Protocol: sqs + Endpoint: !GetAtt Plain.Arn + Tags: + - Key: app + Value: shop + FifoTopic: + Type: AWS::SNS::Topic + Properties: + TopicName: events.fifo + FifoTopic: true + ContentBasedDeduplication: true + FifoThroughputScope: MessageGroup + ArchivePolicy: + MessageRetentionPeriod: "30" + PlainSubscription: + Type: AWS::SNS::Subscription + Properties: + TopicArn: !Ref Alerts + Protocol: sqs + Endpoint: !GetAtt Plain.Arn + RawMessageDelivery: "true" + FilterPolicyScope: MessageAttributes + FilterPolicy: + severity: [high] + RedrivePolicy: + deadLetterTargetArn: !GetAtt DeadLetters.Arn + AlertsPolicy: + Type: AWS::SNS::TopicPolicy + Properties: + Topics: + - !Ref Alerts + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: events.amazonaws.com + Action: sns:Publish + Resource: !Ref Alerts + Bus: + Type: AWS::Events::EventBus + Properties: + Name: shop-bus + Description: Shop events + DeadLetterConfig: + Arn: !GetAtt DeadLetters.Arn + LogConfig: + IncludeDetail: FULL + Level: INFO + Policy: + Version: "2012-10-17" + Statement: + - Sid: AllowAccount + Effect: Allow + Principal: + AWS: !Sub arn:${AWS::Partition}:iam::${AWS::AccountId}:root + Action: events:PutEvents + Resource: !Sub arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/shop-bus + Tags: + - Key: app + Value: shop + OrderPlaced: + Type: AWS::Events::Rule + Properties: + Name: order-placed + Description: Orders to the queue and topic + EventBusName: !Ref Bus + State: ENABLED + EventPattern: + source: [shop.orders] + detail-type: [OrderPlaced] + Targets: + - Id: queue + Arn: !GetAtt Orders.Arn + SqsParameters: + MessageGroupId: orders + DeadLetterConfig: + Arn: !GetAtt DeadLetters.Arn + RetryPolicy: + MaximumEventAgeInSeconds: 3600 + MaximumRetryAttempts: 3 + - Id: topic + Arn: !Ref Alerts + InputTransformer: + InputPathsMap: + id: $.detail.id + InputTemplate: '"Order placed"' + - Id: stream + Arn: !GetAtt Clicks.Arn + RoleArn: !GetAtt EventsRole.Arn + KinesisParameters: + PartitionKeyPath: $.detail.id + Nightly: + Type: AWS::Events::Rule + Properties: + ScheduleExpression: rate(1 day) + Targets: + - Id: machine + Arn: !Ref Workflow + RoleArn: !GetAtt EventsRole.Arn + Input: '{"mode": "nightly"}' + EventsRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: [events.amazonaws.com, states.amazonaws.com] + Action: sts:AssumeRole + Clicks: + Type: AWS::Kinesis::Stream + Properties: + Name: clicks + ShardCount: 2 + RetentionPeriodHours: 48 + DesiredShardLevelMetrics: [IncomingBytes] + StreamEncryption: + EncryptionType: KMS + KeyId: alias/aws/kinesis + StreamModeDetails: + StreamMode: PROVISIONED + Tags: + - Key: app + Value: shop + OnDemand: + Type: AWS::Kinesis::Stream + Properties: + StreamModeDetails: + StreamMode: ON_DEMAND + WorkflowLogs: + Type: AWS::Logs::LogGroup + Properties: + RetentionInDays: 7 + Workflow: + Type: AWS::StepFunctions::StateMachine + Properties: + StateMachineName: order-workflow + StateMachineType: STANDARD + RoleArn: !GetAtt EventsRole.Arn + Definition: + StartAt: Notify + States: + Notify: + Type: Task + Resource: arn:aws:states:::sns:publish + Parameters: + TopicArn: ${TopicArn} + Message.$: $.message + End: true + DefinitionSubstitutions: + TopicArn: !Ref Alerts + LoggingConfiguration: + Level: ERROR + IncludeExecutionData: true + Destinations: + - CloudWatchLogsLogGroup: + LogGroupArn: !GetAtt WorkflowLogs.Arn + TracingConfiguration: + Enabled: true + Tags: + - Key: app + Value: shop + LegacyWorkflow: + Type: AWS::StepFunctions::StateMachine + Properties: + RoleArn: !GetAtt EventsRole.Arn + DefinitionString: !Sub | + { + "StartAt": "Wait", + "States": { + "Wait": {"Type": "Wait", "Seconds": 5, "Next": "Done"}, + "Done": {"Type": "Pass", "Result": "${AWS::Region}", "End": true} + } + } +Outputs: + QueueUrl: + Value: !Ref Orders + QueueName: + Value: !GetAtt Orders.QueueName + TopicArn: + Value: !Ref Alerts + StreamArn: + Value: !GetAtt Clicks.Arn + BusArn: + Value: !GetAtt Bus.Arn + WorkflowArn: + Value: !Ref Workflow diff --git a/services/converter-api/tests/fixtures/cfn/network.yaml b/services/converter-api/tests/fixtures/cfn/network.yaml new file mode 100644 index 0000000..7def37d --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/network.yaml @@ -0,0 +1,368 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: > + A two-tier network: VPC with public and private subnets, an Application Load Balancer + with HTTPS, a Route 53 zone and a CloudFront distribution in front of an S3 bucket. +Parameters: + DomainName: + Type: String + Default: example.com + CertificateArnOverride: + Type: String + Default: "" +Conditions: + HasCertificateOverride: !Not [!Equals [!Ref CertificateArnOverride, ""]] +Resources: + Vpc: + Type: AWS::EC2::VPC + Properties: + CidrBlock: 10.0.0.0/16 + EnableDnsHostnames: true + EnableDnsSupport: true + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-vpc" + PublicSubnetA: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref Vpc + CidrBlock: !Select [0, !Cidr [!GetAtt Vpc.CidrBlock, 4, 8]] + AvailabilityZone: !Select [0, !GetAZs ""] + MapPublicIpOnLaunch: true + PublicSubnetB: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref Vpc + CidrBlock: 10.0.1.0/24 + AvailabilityZone: !Select [1, !GetAZs ""] + MapPublicIpOnLaunch: true + PrivateSubnetA: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref Vpc + CidrBlock: 10.0.2.0/24 + AvailabilityZone: !Select [0, !GetAZs ""] + InternetGateway: + Type: AWS::EC2::InternetGateway + GatewayAttachment: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + VpcId: !Ref Vpc + InternetGatewayId: !Ref InternetGateway + NatEip: + Type: AWS::EC2::EIP + DependsOn: GatewayAttachment + Properties: + Domain: vpc + NatGateway: + Type: AWS::EC2::NatGateway + Properties: + AllocationId: !GetAtt NatEip.AllocationId + SubnetId: !Ref PublicSubnetA + PublicRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref Vpc + PublicRoute: + Type: AWS::EC2::Route + DependsOn: GatewayAttachment + Properties: + RouteTableId: !Ref PublicRouteTable + DestinationCidrBlock: 0.0.0.0/0 + GatewayId: !Ref InternetGateway + PrivateRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref Vpc + PrivateRoute: + Type: AWS::EC2::Route + Properties: + RouteTableId: !Ref PrivateRouteTable + DestinationCidrBlock: 0.0.0.0/0 + NatGatewayId: !Ref NatGateway + PublicSubnetARoutes: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PublicSubnetA + RouteTableId: !Ref PublicRouteTable + PrivateSubnetARoutes: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PrivateSubnetA + RouteTableId: !Ref PrivateRouteTable + S3Endpoint: + Type: AWS::EC2::VPCEndpoint + Properties: + VpcId: !Ref Vpc + ServiceName: !Sub "com.amazonaws.${AWS::Region}.s3" + VpcEndpointType: Gateway + RouteTableIds: [!Ref PrivateRouteTable] + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: "*" + Action: "s3:*" + Resource: "*" + LoadBalancerSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Public HTTPS + VpcId: !Ref Vpc + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + CidrIp: 0.0.0.0/0 + Description: HTTPS from anywhere + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIpv6: ::/0 + AppSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: App servers + VpcId: !Ref Vpc + SecurityGroupEgress: + - IpProtocol: "-1" + CidrIp: 10.0.0.0/16 + BastionSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Bastion, locked down when a certificate override is set + VpcId: !Ref Vpc + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 22 + ToPort: 22 + CidrIp: 10.0.0.0/8 + SecurityGroupEgress: !If + - HasCertificateOverride + - - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + CidrIp: 0.0.0.0/0 + - !Ref AWS::NoValue + AppFromLoadBalancer: + Type: AWS::EC2::SecurityGroupIngress + Properties: + GroupId: !GetAtt AppSecurityGroup.GroupId + IpProtocol: tcp + FromPort: 8080 + ToPort: 8080 + SourceSecurityGroupId: !Ref LoadBalancerSecurityGroup + PublicAcl: + Type: AWS::EC2::NetworkAcl + Properties: + VpcId: !Ref Vpc + PublicAclHttps: + Type: AWS::EC2::NetworkAclEntry + Properties: + NetworkAclId: !Ref PublicAcl + RuleNumber: 100 + Protocol: 6 + RuleAction: allow + CidrBlock: 0.0.0.0/0 + PortRange: {From: 443, To: 443} + PublicAclAssociation: + Type: AWS::EC2::SubnetNetworkAclAssociation + Properties: + NetworkAclId: !Ref PublicAcl + SubnetId: !Ref PublicSubnetB + LoadBalancer: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + Scheme: internet-facing + Type: application + Subnets: [!Ref PublicSubnetA, !Ref PublicSubnetB] + SecurityGroups: [!Ref LoadBalancerSecurityGroup] + LoadBalancerAttributes: + - Key: idle_timeout.timeout_seconds + Value: "120" + - Key: deletion_protection.enabled + Value: "false" + - Key: routing.http2.enabled + Value: "true" + TargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + Port: 8080 + Protocol: HTTP + VpcId: !Ref Vpc + TargetType: ip + HealthCheckPath: /health + HealthCheckIntervalSeconds: 15 + HealthyThresholdCount: 2 + Matcher: + HttpCode: "200-299" + TargetGroupAttributes: + - Key: deregistration_delay.timeout_seconds + Value: "30" + - Key: stickiness.enabled + Value: "true" + - Key: stickiness.lb_cookie.duration_seconds + Value: "3600" + AdminTargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + Port: 8081 + Protocol: HTTP + VpcId: !Ref Vpc + HealthCheckPath: /admin/health + TargetGroupAttributes: + - Key: stickiness.type + Value: app_cookie + - Key: stickiness.app_cookie.cookie_name + Value: ADMIN + - Key: stickiness.app_cookie.duration_seconds + Value: "600" + Certificate: + Type: AWS::CertificateManager::Certificate + Properties: + DomainName: !Ref DomainName + SubjectAlternativeNames: [!Sub "www.${DomainName}"] + ValidationMethod: DNS + DomainValidationOptions: + - DomainName: !Ref DomainName + HostedZoneId: !Ref HostedZone + HttpsListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + LoadBalancerArn: !Ref LoadBalancer + Port: 443 + Protocol: HTTPS + SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06 + Certificates: + - CertificateArn: !If [HasCertificateOverride, !Ref CertificateArnOverride, !Ref Certificate] + DefaultActions: + - Type: forward + TargetGroupArn: !Ref TargetGroup + ForwardConfig: + TargetGroups: + - TargetGroupArn: !Ref TargetGroup + TargetGroupStickinessConfig: + Enabled: true + DurationSeconds: 300 + HttpListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + LoadBalancerArn: !Ref LoadBalancer + Port: 80 + Protocol: HTTP + DefaultActions: + - Type: redirect + RedirectConfig: + Protocol: HTTPS + Port: "443" + StatusCode: HTTP_301 + ApiRule: + Type: AWS::ElasticLoadBalancingV2::ListenerRule + Properties: + ListenerArn: !Ref HttpsListener + Priority: 10 + Conditions: + - Field: path-pattern + PathPatternConfig: + Values: ["/api/*"] + - Field: http-request-method + HttpRequestMethodConfig: + Values: [GET, POST] + Actions: + - Type: fixed-response + FixedResponseConfig: + StatusCode: "503" + ContentType: text/plain + MessageBody: maintenance + HostedZone: + Type: AWS::Route53::HostedZone + Properties: + Name: !Ref DomainName + HostedZoneConfig: + Comment: Public zone + ApiRecord: + Type: AWS::Route53::RecordSet + Properties: + HostedZoneId: !Ref HostedZone + Name: !Sub "api.${DomainName}" + Type: A + AliasTarget: + DNSName: !GetAtt LoadBalancer.DNSName + HostedZoneId: !GetAtt LoadBalancer.CanonicalHostedZoneID + EvaluateTargetHealth: true + MailRecords: + Type: AWS::Route53::RecordSetGroup + Properties: + HostedZoneId: !Ref HostedZone + RecordSets: + - Name: !Ref DomainName + Type: MX + TTL: "300" + ResourceRecords: ["10 mail.example.com"] + - Name: !Ref DomainName + Type: TXT + TTL: "300" + ResourceRecords: ['"v=spf1 -all"'] + SiteBucket: + Type: AWS::S3::Bucket + OriginAccessControl: + Type: AWS::CloudFront::OriginAccessControl + Properties: + OriginAccessControlConfig: + Name: !Sub "${AWS::StackName}-site" + OriginAccessControlOriginType: s3 + SigningBehavior: always + SigningProtocol: sigv4 + Distribution: + Type: AWS::CloudFront::Distribution + Properties: + DistributionConfig: + Enabled: true + Comment: Static site + DefaultRootObject: index.html + PriceClass: PriceClass_100 + HttpVersion: http2and3 + IPV6Enabled: true + Origins: + - Id: site + DomainName: !GetAtt SiteBucket.RegionalDomainName + OriginAccessControlId: !GetAtt OriginAccessControl.Id + S3OriginConfig: + OriginAccessIdentity: "" + - Id: api + DomainName: !GetAtt LoadBalancer.DNSName + CustomOriginConfig: + OriginProtocolPolicy: https-only + OriginSSLProtocols: [TLSv1.2] + DefaultCacheBehavior: + TargetOriginId: site + ViewerProtocolPolicy: redirect-to-https + CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 + Compress: true + FunctionAssociations: !If + - HasCertificateOverride + - - EventType: viewer-request + FunctionARN: !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:function/redirect + - !Ref AWS::NoValue + CacheBehaviors: + - PathPattern: /api/* + TargetOriginId: api + ViewerProtocolPolicy: https-only + AllowedMethods: [GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE] + ForwardedValues: + QueryString: true + Headers: [Authorization] + CustomErrorResponses: + - ErrorCode: 404 + ResponseCode: 200 + ResponsePagePath: /index.html +Outputs: + VpcId: + Value: !Ref Vpc + LoadBalancerDns: + Value: !GetAtt LoadBalancer.DNSName + NameServers: + Value: !Join [",", !GetAtt HostedZone.NameServers] + DistributionDomain: + Value: !GetAtt Distribution.DomainName + CertificateArn: + Value: !Ref Certificate diff --git a/services/converter-api/tests/fixtures/cfn/observability.yaml b/services/converter-api/tests/fixtures/cfn/observability.yaml new file mode 100644 index 0000000..461f251 --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/observability.yaml @@ -0,0 +1,159 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Log groups, filters, alarms and a dashboard +Parameters: + Environment: + Type: String + Default: dev +Conditions: + IsProd: !Equals [!Ref Environment, prod] +Resources: + AppLogs: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: /shop/app + RetentionInDays: "30" + LogGroupClass: STANDARD + DeletionProtectionEnabled: false + Tags: + - Key: app + Value: shop + ErrorCount: + Type: AWS::Logs::MetricFilter + Properties: + FilterName: errors + LogGroupName: !Ref AppLogs + FilterPattern: ERROR + MetricTransformations: + - MetricName: Errors + MetricNamespace: Shop + MetricValue: "1" + DefaultValue: 0 + Unit: Count + LatencyFilter: + Type: AWS::Logs::MetricFilter + Properties: + LogGroupName: !Ref AppLogs + FilterPattern: "{ $.latency = * }" + MetricTransformations: + - MetricName: Latency + MetricNamespace: Shop + MetricValue: $.latency + Dimensions: + - Key: Route + Value: $.route + Forward: + Type: AWS::Logs::SubscriptionFilter + Properties: + FilterName: to-stream + LogGroupName: !Ref AppLogs + FilterPattern: "" + DestinationArn: !GetAtt LogStream.Arn + RoleArn: !GetAtt LogsRole.Arn + Distribution: ByLogStream + LogStream: + Type: AWS::Kinesis::Stream + Properties: + Name: logs + ShardCount: 1 + LogsRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: logs.amazonaws.com + Action: sts:AssumeRole + Policies: + - PolicyName: write-logs + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: logs:PutLogEvents + Resource: !GetAtt AppLogs.Arn + Alarms: + Type: AWS::SNS::Topic + ErrorAlarm: + Type: AWS::CloudWatch::Alarm + Properties: + AlarmName: shop-errors + AlarmDescription: Too many errors + ActionsEnabled: true + AlarmActions: [!Ref Alarms, !If [IsProd, !Ref Alarms, !Ref AWS::NoValue]] + OKActions: [!Ref Alarms] + InsufficientDataActions: [!Ref Alarms] + ComparisonOperator: GreaterThanThreshold + EvaluationPeriods: 3 + DatapointsToAlarm: 2 + MetricName: Errors + Namespace: Shop + Period: 60 + Statistic: Sum + Threshold: "5" + TreatMissingData: notBreaching + Unit: Count + Dimensions: + - Name: Service + Value: app + Tags: + - Key: app + Value: shop + LatencyAlarm: + Type: AWS::CloudWatch::Alarm + Properties: + ComparisonOperator: GreaterThanThreshold + EvaluationPeriods: 1 + Threshold: 500 + ExtendedStatistic: p99 + MetricName: Latency + Namespace: Shop + Period: 300 + EvaluateLowSampleCountPercentile: ignore + RatioAlarm: + Type: AWS::CloudWatch::Alarm + Properties: + AlarmName: error-ratio + ComparisonOperator: GreaterThanThreshold + EvaluationPeriods: 1 + Threshold: 0.05 + Metrics: + - Id: ratio + Expression: errors / requests + Label: Error ratio + ReturnData: true + - Id: errors + ReturnData: false + MetricStat: + Metric: + MetricName: Errors + Namespace: Shop + Dimensions: + - Name: Service + Value: app + Period: 60 + Stat: Sum + Unit: Count + - Id: requests + ReturnData: false + MetricStat: + Metric: + MetricName: Requests + Namespace: Shop + Period: 60 + Stat: Sum + Dashboard: + Type: AWS::CloudWatch::Dashboard + Properties: + DashboardName: shop + DashboardBody: !Sub '{"widgets": [{"type": "text", "x": 0, "y": 0, "width": 6, "height": 3, "properties": {"markdown": "Shop in ${AWS::Region}"}}]}' + PlainDashboard: + Type: AWS::CloudWatch::Dashboard + Properties: + DashboardBody: '{"widgets": []}' +Outputs: + LogGroupArn: + Value: !GetAtt AppLogs.Arn + AlarmArn: + Value: !GetAtt ErrorAlarm.Arn diff --git a/services/converter-api/tests/fixtures/cfn/sam.yaml b/services/converter-api/tests/fixtures/cfn/sam.yaml new file mode 100644 index 0000000..db38923 --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/sam.yaml @@ -0,0 +1,113 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: Orders service +Globals: + Function: + Runtime: python3.13 + Timeout: 10 + Environment: + Variables: + TABLE: !Ref Orders +Resources: + Orders: + Type: AWS::Serverless::SimpleTable + Uploads: + Type: AWS::S3::Bucket + Topic: + Type: AWS::SNS::Topic + ApiFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: ./src/api/ + Handler: app.handler + Environment: + Variables: + MODE: api + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref Orders + - AWSLambdaVPCAccessExecutionRole + - Statement: + - Effect: Allow + Action: sns:Publish + Resource: !Ref Topic + Events: + GetOrders: + Type: Api + Properties: + Path: /orders/{id} + Method: get + Http: + Type: HttpApi + Properties: + Path: /h + Method: post + Nightly: + Type: Schedule + Properties: + Schedule: rate(1 day) + Upload: + Type: S3 + Properties: + Bucket: !Ref Uploads + Events: s3:ObjectCreated:* + Filter: + S3Key: + Rules: + - Name: suffix + Value: .csv + Notify: + Type: SNS + Properties: + Topic: !Ref Topic + FunctionUrlConfig: + AuthType: NONE + AutoPublishAlias: live + Worker: + Type: AWS::Serverless::Function + Connectors: + ToTopic: + Properties: + Destination: + Id: Topic + Permissions: [Write] + Properties: + InlineCode: | + def handler(event, context): + return "ok" + Handler: index.handler + Events: + Stream: + Type: DynamoDB + Properties: + Stream: !GetAtt Table2.StreamArn + StartingPosition: LATEST + Table2: + Type: AWS::DynamoDB::Table + Properties: + AttributeDefinitions: [{AttributeName: id, AttributeType: S}] + KeySchema: [{AttributeName: id, KeyType: HASH}] + BillingMode: PAY_PER_REQUEST + StreamSpecification: {StreamViewType: NEW_IMAGE} + Flow: + Type: AWS::Serverless::StateMachine + Properties: + Definition: + StartAt: Call + States: + Call: + Type: Task + Resource: arn:aws:states:::lambda:invoke + Parameters: + FunctionName: ${Fn} + End: true + DefinitionSubstitutions: + Fn: !GetAtt Worker.Arn + Policies: + - LambdaInvokePolicy: + FunctionName: !Ref Worker +Outputs: + ApiUrl: + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" + AliasArn: + Value: !Ref ApiFunction.Alias diff --git a/services/converter-api/tests/fixtures/cfn/storage.yaml b/services/converter-api/tests/fixtures/cfn/storage.yaml new file mode 100644 index 0000000..87564ff --- /dev/null +++ b/services/converter-api/tests/fixtures/cfn/storage.yaml @@ -0,0 +1,310 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: S3, DynamoDB and ECR with most of their options +Parameters: + Retention: + Type: Number + Default: 90 +Conditions: + WithWebsite: !Equals [!Ref AWS::Region, us-east-1] +Resources: + Logs: + Type: AWS::S3::Bucket + Properties: + OwnershipControls: + Rules: + - ObjectOwnership: BucketOwnerPreferred + AccessControl: LogDeliveryWrite + Assets: + Type: AWS::S3::Bucket + DependsOn: AssetsPermission + Properties: + BucketName: !Sub "assets-${AWS::AccountId}" + ObjectLockEnabled: true + ObjectLockConfiguration: + ObjectLockEnabled: Enabled + Rule: + DefaultRetention: + Mode: GOVERNANCE + Days: 30 + VersioningConfiguration: + Status: Enabled + AccelerateConfiguration: + AccelerationStatus: Enabled + BucketEncryption: + ServerSideEncryptionConfiguration: + - BucketKeyEnabled: true + ServerSideEncryptionByDefault: + SSEAlgorithm: aws:kms + KMSMasterKeyID: alias/aws/s3 + PublicAccessBlockConfiguration: + BlockPublicAcls: true + BlockPublicPolicy: true + IgnorePublicAcls: true + RestrictPublicBuckets: true + LoggingConfiguration: + DestinationBucketName: !Ref Logs + LogFilePrefix: assets/ + LifecycleConfiguration: + Rules: + - Id: archive + Status: Enabled + Prefix: reports/ + Transitions: + - StorageClass: STANDARD_IA + TransitionInDays: 30 + Transition: + StorageClass: GLACIER + TransitionInDays: 90 + NoncurrentVersionExpiration: + NoncurrentDays: 365 + NewerNoncurrentVersions: 3 + NoncurrentVersionTransitions: + - StorageClass: GLACIER + TransitionInDays: 30 + NewerNoncurrentVersions: 1 + AbortIncompleteMultipartUpload: + DaysAfterInitiation: 7 + - Status: Enabled + TagFilters: + - Key: temp + Value: "true" + ExpirationInDays: !Ref Retention + - Status: Enabled + Prefix: tmp/ + ObjectSizeGreaterThan: 1024 + ExpirationDate: "2030-01-01T00:00:00Z" + - Status: Enabled + ObjectSizeLessThan: 128 + ExpiredObjectDeleteMarker: true + - Status: Enabled + ObjectSizeGreaterThan: 10 + NoncurrentVersionExpirationInDays: 30 + - Id: conditional + Status: Enabled + Prefix: media/ + Transitions: + - !If + - WithWebsite + - StorageClass: GLACIER + TransitionInDays: 60 + - !Ref AWS::NoValue + NoncurrentVersionExpiration: !If + - WithWebsite + - NoncurrentDays: 30 + - !Ref AWS::NoValue + AbortIncompleteMultipartUpload: !If + - WithWebsite + - DaysAfterInitiation: 3 + - !Ref AWS::NoValue + CorsConfiguration: + CorsRules: + - Id: web + AllowedMethods: [GET, HEAD] + AllowedOrigins: ["https://example.com"] + AllowedHeaders: ["*"] + ExposedHeaders: [ETag] + MaxAge: "3600" + NotificationConfiguration: + LambdaConfigurations: + - Event: s3:ObjectCreated:* + Function: arn:aws:lambda:us-east-1:123456789012:function:resize + Filter: + S3Key: + Rules: + - Name: prefix + Value: uploads/ + - Name: suffix + Value: .jpg + QueueConfigurations: + - Event: s3:ObjectRemoved:* + Queue: arn:aws:sqs:us-east-1:123456789012:removed + TopicConfigurations: + - Event: s3:ObjectRestore:Completed + Topic: arn:aws:sns:us-east-1:123456789012:restored + EventBridgeConfiguration: !If + - WithWebsite + - EventBridgeEnabled: true + - !Ref AWS::NoValue + Tags: + - Key: team + Value: media + AssetsPermission: + Type: AWS::SNS::Topic + Site: + Type: AWS::S3::Bucket + Condition: WithWebsite + Properties: + WebsiteConfiguration: + IndexDocument: index.html + ErrorDocument: error.html + RoutingRules: + - RoutingRuleCondition: + KeyPrefixEquals: docs/ + RedirectRule: + ReplaceKeyPrefixWith: documents/ + HttpRedirectCode: "301" + Redirect: + Type: AWS::S3::Bucket + Properties: + WebsiteConfiguration: + RedirectAllRequestsTo: + HostName: example.com + Protocol: https + LoggingConfiguration: {} + SitePolicy: + Type: AWS::S3::BucketPolicy + Condition: WithWebsite + Properties: + Bucket: !Ref Site + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: "*" + Action: s3:GetObject + Resource: !Sub "${Site.Arn}/*" + Orders: + Type: AWS::DynamoDB::Table + Properties: + TableName: orders + BillingMode: PROVISIONED + ProvisionedThroughput: + ReadCapacityUnits: 5 + WriteCapacityUnits: 5 + AttributeDefinitions: + - AttributeName: pk + AttributeType: S + - AttributeName: sk + AttributeType: S + - AttributeName: status + AttributeType: S + - AttributeName: created + AttributeType: N + KeySchema: + - AttributeName: pk + KeyType: HASH + - AttributeName: sk + KeyType: RANGE + GlobalSecondaryIndexes: + - IndexName: by-status + KeySchema: + - AttributeName: status + KeyType: HASH + - AttributeName: created + KeyType: RANGE + Projection: + ProjectionType: INCLUDE + NonKeyAttributes: [total] + ProvisionedThroughput: + ReadCapacityUnits: 2 + WriteCapacityUnits: 2 + LocalSecondaryIndexes: + - IndexName: by-created + KeySchema: + - AttributeName: pk + KeyType: HASH + - AttributeName: created + KeyType: RANGE + Projection: + ProjectionType: KEYS_ONLY + StreamSpecification: + StreamViewType: NEW_AND_OLD_IMAGES + TimeToLiveSpecification: + AttributeName: expires + Enabled: true + SSESpecification: + SSEEnabled: true + SSEType: KMS + PointInTimeRecoverySpecification: + PointInTimeRecoveryEnabled: true + RecoveryPeriodInDays: 14 + TableClass: STANDARD + DeletionProtectionEnabled: true + Tags: + - Key: team + Value: shop + Events: + Type: AWS::DynamoDB::Table + Properties: + BillingMode: PAY_PER_REQUEST + AttributeDefinitions: + - AttributeName: id + AttributeType: S + - !If + - WithWebsite + - AttributeName: kind + AttributeType: S + - !Ref AWS::NoValue + KeySchema: + - AttributeName: id + KeyType: HASH + StreamSpecification: !If + - WithWebsite + - StreamViewType: KEYS_ONLY + - !Ref AWS::NoValue + SSESpecification: + SSEEnabled: true + KMSMasterKeyId: alias/shop-events + OnDemandThroughput: + MaxReadRequestUnits: 100 + MaxWriteRequestUnits: 50 + GlobalSecondaryIndexes: + - IndexName: everything + KeySchema: + - AttributeName: id + KeyType: HASH + Projection: {} + OnDemandThroughput: + MaxReadRequestUnits: 10 + MaxWriteRequestUnits: 10 + - !If + - WithWebsite + - IndexName: by-kind + KeySchema: + - AttributeName: kind + KeyType: HASH + Projection: + ProjectionType: KEYS_ONLY + - !Ref AWS::NoValue + Images: + Type: AWS::ECR::Repository + Properties: + RepositoryName: shop/images + ImageTagMutability: IMMUTABLE + EmptyOnDelete: true + ImageScanningConfiguration: + ScanOnPush: true + EncryptionConfiguration: + EncryptionType: KMS + LifecyclePolicy: + LifecyclePolicyText: '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"untagged","countType":"sinceImagePushed","countUnit":"days","countNumber":14},"action":{"type":"expire"}}]}' + RepositoryPolicyText: + Version: "2012-10-17" + Statement: + - Sid: pull + Effect: Allow + Principal: + AWS: arn:aws:iam::123456789012:root + Action: [ecr:BatchGetImage, ecr:GetDownloadUrlForLayer] + Tags: + - Key: team + Value: shop + Cache: + Type: AWS::ECR::Repository + Properties: + LifecyclePolicy: !If + - WithWebsite + - LifecyclePolicyText: '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"any","countType":"imageCountMoreThan","countNumber":5},"action":{"type":"expire"}}]}' + - !Ref AWS::NoValue +Outputs: + AssetsArn: + Value: !GetAtt Assets.Arn + AssetsDomain: + Value: !GetAtt Assets.RegionalDomainName + SiteUrl: + Condition: WithWebsite + Value: !GetAtt Site.WebsiteURL + OrdersStream: + Value: !GetAtt Orders.StreamArn + ImagesUri: + Value: !GetAtt Images.RepositoryUri diff --git a/services/converter-api/tests/test_api.py b/services/converter-api/tests/test_api.py index ce27c9f..580365b 100644 --- a/services/converter-api/tests/test_api.py +++ b/services/converter-api/tests/test_api.py @@ -9,7 +9,9 @@ import yaml from fastapi.testclient import TestClient -from main import MAX_INPUT_CHARS, app, configure_logging, resolve_log_level +import main +from main import app, configure_logging, resolve_log_level +from schemas import MAX_INPUT_CHARS client = TestClient(app) @@ -132,7 +134,7 @@ def test_resolve_log_level_unknown_falls_back_to_info(): def test_unknown_log_level_does_not_crash_startup(): # Importing main with a bad LOG_LEVEL used to raise "ValueError: Unknown level". - env = {**os.environ, "LOG_LEVEL": "verbose"} + env = dict(os.environ, LOG_LEVEL="verbose") service_dir = Path(__file__).resolve().parents[1] # works from any working directory result = subprocess.run( [sys.executable, "-c", "import main"], @@ -229,3 +231,83 @@ def test_convert_error_carries_line_and_column_for_yaml_syntax_errors(): response = client.post("/convert/compose-to-k8s/files", json={"compose_yaml": "services: {}"}) assert response.status_code == 400 assert "line" not in response.json() + + +# --- CloudFormation -> Terraform --------------------------------------------------------- + +CFN = ( + "Resources:\n" + " Bucket:\n" + " Type: AWS::S3::Bucket\n" + " Properties:\n" + " BucketName: !Sub '${AWS::StackName}-b'\n" +) + + +def test_cfn_to_terraform(): + response = client.post( + "/convert/cfn-to-terraform", json={"template": CFN, "stack_name": "shop"} + ) + assert response.status_code == 200 + body = response.json() + assert body["success"] is True and body["source"] == "cloudformation" + paths = [f["path"] for f in body["files"]] + assert paths == ["versions.tf", "variables.tf", "main.tf"] + assert 'resource "aws_s3_bucket" "bucket"' in body["files"][2]["content"] + assert 'default = "shop"' in body["files"][1]["content"] + assert body["summary"] == {"resources": 1, "aws": 1, "awscc": 0, "unsupported": 0} + assert body["resources"] == [ + { + "logical_id": "Bucket", + "type": "AWS::S3::Bucket", + "address": "aws_s3_bucket.bucket", + "status": "aws", + } + ] + + +def test_cfn_to_terraform_options(): + response = client.post( + "/convert/cfn-to-terraform", + json={"template": CFN, "provider": "awscc", "layout": "single", "include_imports": True}, + ) + body = response.json() + assert [f["path"] for f in body["files"]] == ["main.tf"] + assert ( + "awscc_s3_bucket" in body["files"][0]["content"] + and "import {" in body["files"][0]["content"] + ) + + +def test_cfn_to_terraform_rejects_bad_templates_with_position(): + response = client.post("/convert/cfn-to-terraform", json={"template": "Resources: [1\n"}) + assert response.status_code == 400 + body = response.json() + assert body["success"] is False and body["error"].startswith("Invalid YAML") + assert body["line"] == 2 + + +@pytest.mark.parametrize( + "payload", + [ + {"template": CFN, "provider": "google"}, + {"template": CFN, "layout": "tree"}, + {"template": CFN, "stack_name": "1-bad"}, + {"template": "x" * 500_001}, + ], +) +def test_cfn_to_terraform_validation(payload): + assert client.post("/convert/cfn-to-terraform", json=payload).status_code == 422 + + +def broken_convert(template, provider, layout, stack_name, include_imports): + raise KeyError("x") + + +def test_cfn_to_terraform_unexpected_shape_is_a_400(monkeypatch, caplog): + monkeypatch.setattr(main, "convert_template", broken_convert) + with caplog.at_level("ERROR", logger="converter-api"): + response = client.post("/convert/cfn-to-terraform", json={"template": CFN}) + assert response.status_code == 400 + assert "cannot handle yet" in response.json()["error"] + assert "unexpected template shape" in caplog.text diff --git a/services/converter-api/tests/test_cfn_apigateway.py b/services/converter-api/tests/test_cfn_apigateway.py new file mode 100644 index 0000000..821513b --- /dev/null +++ b/services/converter-api/tests/test_cfn_apigateway.py @@ -0,0 +1,423 @@ +"""API Gateway mappings (converters/cfn/resources/apigateway.py).""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest +import yaml + +from converters.cfn.pipeline import convert_template +from converters.cfn.resources.apigateway import method_path, name_suffix + +FIXTURE = Path(__file__).parent / "fixtures" / "cfn" / "apigateway.yaml" + + +def convert(resources: dict) -> tuple[str, list[str]]: + result = convert_template(yaml.safe_dump({"Resources": resources}), stack_name="demo") + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + return main, result["notes"] + + +def test_fixture_converts_everything(): + result = convert_template(FIXTURE.read_text(), stack_name="demo") + assert result["summary"]["unsupported"] == 0 + assert not [n for n in result["notes"] if "was not converted" in n] + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + assert "redeployment = sha1(aws_api_gateway_rest_api.spec_api.body)" in main + assert 'resource "aws_api_gateway_stage" "spec_deployment_stage"' in main + assert 'method_path = "orders/GET"' in main + assert 'method_path = "~1/GET"' in main + assert 'dynamic "request_parameter"' in main and 'dynamic "route_settings"' in main + assert main.count("count = local.debugging ? 1 : 0") == 3 + assert '"get_orders_integration_response_200"' in main + assert 'name = "spec-http"' in main + outputs = next(f["content"] for f in result["files"] if f["path"] == "outputs.tf") + assert "aws_api_gateway_stage.prod.stage_name" in outputs + + +@pytest.mark.parametrize( + ("path", "method", "expected"), + [ + ("/*", "*", "*/*"), + ("/~1pets~1{id}", "GET", "pets/{id}/GET"), + ("/", "POST", "~1/POST"), + ({"Ref": "X"}, "GET", None), + ], +) +def test_method_path(path, method, expected): + assert method_path(path, method) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), [("200", "_200"), (404, "_404"), ("!!", "_3"), (True, "_3")] +) +def test_suffix(value, expected): + assert name_suffix(value, 3) == expected + + +def test_rest_api_defaults_and_body_location(): + main, notes = convert( + { + "Api": { + "Type": "AWS::ApiGateway::RestApi", + "Properties": { + "BodyS3Location": {"Bucket": "b", "Key": "k"}, + "MinimumCompressionSize": {"Ref": "AWS::Region"}, + "Body": {"info": "not a mapping"}, + }, + }, + "NoBody": {"Type": "AWS::ApiGateway::RestApi"}, + } + ) + assert 'name = "${var.stack_name}-Api"' in main + assert "minimum_compression_size = data.aws_region.current.region" in main + assert any("Api: BodyS3Location was not converted" in n for n in notes) + assert any("NoBody had no Name" in n for n in notes) + + +def test_deployment_triggers_only_for_apis_with_a_body(): + main, notes = convert( + { + "Queue": {"Type": "AWS::SQS::Queue"}, + "Api": {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": "a"}}, + "ToQueue": { + "Type": "AWS::ApiGateway::Deployment", + "Properties": {"RestApiId": {"Ref": "Queue"}}, + }, + "ToApi": { + "Type": "AWS::ApiGateway::Deployment", + "Properties": {"RestApiId": {"Ref": "Api"}, "StageName": "dev"}, + }, + "ToId": {"Type": "AWS::ApiGateway::Deployment", "Properties": {"RestApiId": "abc"}}, + } + ) + assert "triggers" not in main + assert sum("only redeployed when its arguments change" in n for n in notes) == 3 + assert 'stage_name = "dev"' in main + + +def test_stage_method_settings_with_computed_path(): + main, notes = convert( + { + "Stage": { + "Type": "AWS::ApiGateway::Stage", + "Properties": { + "RestApiId": "abc", + "DeploymentId": "d", + "MethodSettings": [{"ResourcePath": {"Ref": "AWS::Region"}, "Odd": 1}], + }, + } + } + ) + assert 'stage_name = "${var.stack_name}-Stage"' in main + assert 'method_path = "*/*"' in main + assert any("MethodSettings[0] uses a computed path" in n for n in notes) + assert any("'Stage.MethodSettings[0].Odd' was not converted" in n for n in notes) + + +def test_method_without_integration_and_unmatched_responses(): + main, _ = convert( + { + "Plain": { + "Type": "AWS::ApiGateway::Method", + "Properties": {"RestApiId": "a", "ResourceId": "r", "HttpMethod": "GET"}, + }, + "Proxy": { + "Type": "AWS::ApiGateway::Method", + "Properties": { + "RestApiId": "a", + "ResourceId": "r", + "HttpMethod": "ANY", + "MethodResponses": [{"StatusCode": {"Ref": "AWS::Region"}}], + "Integration": { + "Type": "HTTP_PROXY", + "IntegrationResponses": [{"StatusCode": "500"}], + }, + }, + }, + } + ) + assert "plain_integration" not in main + assert '"proxy_response_0"' in main + assert "depends_on = [aws_api_gateway_integration.proxy_integration]" in main + + +def test_http_api_defaults_route_parameters_and_stage_settings(): + main, _ = convert( + { + "Api": {"Type": "AWS::ApiGatewayV2::Api", "Properties": {"Name": "a"}}, + "Route": { + "Type": "AWS::ApiGatewayV2::Route", + "Properties": { + "ApiId": {"Ref": "Api"}, + "RouteKey": "$connect", + "RequestParameters": {"a": "true", "b": False, "c": {"Required": "false"}}, + }, + }, + "Stage": { + "Type": "AWS::ApiGatewayV2::Stage", + "Properties": {"ApiId": {"Ref": "Api"}, "RouteSettings": "computed"}, + }, + "Auth": { + "Type": "AWS::ApiGatewayV2::Authorizer", + "Properties": {"ApiId": {"Ref": "Api"}, "AuthorizerType": "REQUEST"}, + }, + } + ) + assert 'protocol_type = "HTTP"' in main + assert main.count("required = true") == 1 + assert main.count("required = false") == 2 + assert 'name = "${var.stack_name}-Stage"' in main + assert 'name = "${var.stack_name}-Auth"' in main + + +# --- regression tests for the review findings ------------------------------------------- + +NO = {"Ref": "AWS::NoValue"} +API = {"Type": "AWS::ApiGateway::RestApi", "Properties": {"Name": "a"}} +HTTP = {"Type": "AWS::ApiGatewayV2::Api", "Properties": {"Name": "h", "ProtocolType": "HTTP"}} +EVIL = 'x" ${file("/etc/passwd")} y' + + +def convert_with_condition(resources: dict) -> tuple[str, list[str]]: + template = { + "Parameters": {"Env": {"Type": "String"}, "List": {"Type": "String"}}, + "Conditions": {"On": {"Fn::Equals": [{"Ref": "Env"}, "on"]}}, + "Resources": resources, + } + result = convert_template(yaml.safe_dump(template), stack_name="demo") + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + return main, result["notes"] + + +def optional(value): + return {"Fn::If": ["On", value, NO]} + + +def assert_no_injection(main: str) -> None: + code = "\n".join(line for line in main.splitlines() if not line.lstrip().startswith("#")) + assert 'file("' not in code + assert not re.search(r"(? dict: + out = {"aws:cdk:path": path} + out.update(extra or {}) + return out + + +def test_fixture(): + result = convert_template(FIXTURE.read_text(), stack_name="web") + assert result["source"] == "cdk" + assert result["summary"] == {"resources": 6, "aws": 6, "awscc": 0, "unsupported": 0} + files = {f["path"]: f["content"] for f in result["files"]} + main = files["main.tf"] + assert 'resource "aws_s3_bucket" "site_bucket" {\n force_destroy = true\n}' in main + assert "aws-cdk:auto-delete-objects" not in main + assert "custom_s3_auto_delete" not in main # the helper function and role are gone + assert 'resource "aws_cloudwatch_log_group" "api_handler_log_retention"' in main + assert "retention_in_days = 14" in main + assert 'source_dir = "${path.module}/cdk.out/asset.3b1f' in main + assert 'resource "aws_iam_role_policy" "api_handler_service_role_default_policy"' in main + assert main.count("Principal") == 2 # the provider role's bucket policy statement is gone + assert "bootstrap" not in files.get("variables.tf", "").lower() + assert "locals.tf" not in files # CDKMetadataAvailable is unused once CDKMetadata is gone + notes = "\n".join(result["notes"]) + assert "force_destroy" in notes and "log group" in notes and "cdk.out" in notes + + +def test_path_names(): + assert path_name("Stack/Api/Handler/Resource") == "Api_Handler" + assert path_name("Stack/Table/Default") == "Table" + assert path_name("Stack/Resource") is None + assert path_name("Stack/Custom::Thing/Role") == "Custom_Thing_Role" + + +def testreferences(): + names = {"A"} + assert references({"Ref": "A"}, names) + assert references({"Fn::GetAtt": ["A", "Arn"]}, names) + assert references({"Fn::GetAtt": "A.Arn"}, names) + assert references({"Fn::Sub": "${A.Arn}/x"}, names) + assert references({"Fn::Sub": ["${A}", {}]}, names) + assert not references({"Fn::Sub": "${AB}"}, names) + assert not references({"Fn::Sub": [1, {}]}, names) + assert references([{"x": {"Ref": "A"}}], names) + assert not references("A", names) + + +def test_restrict_default_security_group_and_shared_providers(): + template = { + "Resources": { + "Vpc": { + "Type": "AWS::EC2::VPC", + "Properties": {"CidrBlock": "10.0.0.0/16"}, + "Metadata": meta("S/Vpc/Resource"), + }, + "Restrict": { + "Type": "Custom::VpcRestrictDefaultSG", + "Properties": { + "ServiceToken": {"Fn::GetAtt": "Provider.Arn"}, + "DefaultSecurityGroupId": {"Fn::GetAtt": ["Vpc", "DefaultSecurityGroup"]}, + }, + "Metadata": meta("S/Vpc/RestrictDefaultSecurityGroupCustomResource/Default"), + }, + "Provider": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Role": {"Fn::GetAtt": "ProviderRole.Arn"}, + "Handler": "i.h", + "Runtime": "nodejs22.x", + "Code": {"ZipFile": "x"}, + }, + "Metadata": meta("S/Custom::VpcRestrictDefaultSGCustomResourceProvider/Handler"), + }, + "ProviderRole": { + "Type": "AWS::IAM::Role", + "Properties": {"AssumeRolePolicyDocument": {}}, + "Metadata": meta("S/Custom::VpcRestrictDefaultSGCustomResourceProvider/Role"), + }, + "UsesRole": { + "Type": "AWS::SNS::Topic", + "Properties": {"TopicName": {"Fn::GetAtt": ["ProviderRole", "Arn"]}}, + "DependsOn": ["Restrict"], + }, + "Unnamed": {"Type": "AWS::SQS::Queue", "Metadata": {"aws:cdk:path": "S/Resource"}}, + "NoMeta": {"Type": "AWS::SQS::Queue", "Metadata": "x"}, + } + } + notes: list[str] = [] + out, names, _ = prepare_cdk(template, notes) + resources = out["Resources"] + assert "Restrict" not in resources and "Provider" not in resources + assert "ProviderRole" in resources # still referenced by UsesRole + assert "DependsOn" not in resources["UsesRole"] + assert names == { + "Vpc": "Vpc", + "ProviderRole": "Custom_VpcRestrictDefaultSGCustomResourceProvider_Role", + } + assert any("aws_default_security_group" in n for n in notes) + + +def test_auto_delete_with_an_external_bucket_and_kept_conditions(): + template = { + "Conditions": { + "CDKMetadataAvailable": {"Fn::Equals": ["a", "a"]}, + "Other": {"Fn::Equals": ["a", "b"]}, + }, + "Resources": { + "AutoDelete": { + "Type": "Custom::S3AutoDeleteObjects", + "Properties": {"ServiceToken": "arn:literal", "BucketName": "external-bucket"}, + }, + "Queue": { + "Type": "AWS::SQS::Queue", + "Condition": "CDKMetadataAvailable", + "Properties": {"DelaySeconds": {"Fn::If": ["CDKMetadataAvailable", 1, 2]}}, + }, + "Tagged": { + "Type": "AWS::S3::Bucket", + "Properties": { + "Tags": [ + {"Key": "aws-cdk:auto-delete-objects", "Value": "true"}, + {"Key": "k", "Value": "v"}, + ] + }, + }, + "Policy": { + "Type": "AWS::S3::BucketPolicy", + "Properties": {"Bucket": "b", "PolicyDocument": "{}"}, + }, + "Meta": {"Type": "AWS::CDK::Metadata", "Condition": "CDKMetadataAvailable"}, + }, + "Parameters": {"BootstrapVersion": {"Type": "String"}, "Keep": {"Type": "String"}}, + "Rules": {"CheckBootstrapVersion": {}, "Mine": {}}, + } + notes: list[str] = [] + out, _, _ = prepare_cdk(template, notes) + assert "CDKMetadataAvailable" in out["Conditions"] # still used by Queue + assert out["Parameters"] == {"Keep": {"Type": "String"}} + assert out["Rules"] == {"Mine": {}} + assert "Meta" not in out["Resources"] and "AutoDelete" not in out["Resources"] + resource = out["Resources"]["Tagged"] + drop_tag(resource, "aws-cdk:auto-delete-objects") + assert resource["Properties"]["Tags"] == [{"Key": "k", "Value": "v"}] + result = convert_template(json.dumps(template)) + assert any("Rules of the template were not converted" in n for n in result["notes"]) + + +def test_unused_cdk_condition_is_removed_and_empty_policy_dropped(): + template = { + "Conditions": {"CDKMetadataAvailable": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Bucket": {"Type": "AWS::S3::Bucket", "Metadata": meta("S/Bucket/Resource")}, + "AutoDelete": { + "Type": "Custom::S3AutoDeleteObjects", + "Properties": { + "ServiceToken": {"Fn::GetAtt": ["Provider", "Arn"]}, + "BucketName": {"Ref": "Bucket"}, + }, + }, + "Provider": {"Type": "AWS::Lambda::Function", "Properties": {}}, + "OnlyProvider": { + "Type": "AWS::S3::BucketPolicy", + "Properties": { + "Bucket": {"Ref": "Bucket"}, + "PolicyDocument": { + "Statement": [{"Principal": {"AWS": {"Fn::GetAtt": ["Provider", "Arn"]}}}] + }, + }, + "DependsOn": "Provider", + }, + "Layer": { + "Type": "AWS::Lambda::LayerVersion", + "Properties": {"Content": {"S3Bucket": "b", "S3Key": "k"}}, + "Metadata": meta( + "S/Layer/Resource", + {"aws:asset:path": "asset.1", "aws:asset:property": "Content"}, + ), + }, + "Image": { + "Type": "AWS::Lambda::Function", + "Properties": {"Code": {"ImageUri": "x"}}, + "Metadata": meta( + "S/Image/Resource", + {"aws:asset:path": "asset.2", "aws:asset:property": "Code.ImageUri"}, + ), + }, + "Meta": {"Type": "AWS::CDK::Metadata", "Condition": "CDKMetadataAvailable"}, + }, + } + notes: list[str] = [] + out, names, hints = prepare_cdk(template, notes) + assert "Conditions" not in out + assert "OnlyProvider" not in out["Resources"] + assert hints == {"Bucket": {"force_destroy": True}, "Layer": {"code_path": "cdk.out/asset.1"}} + assert "Content" not in out["Resources"]["Layer"]["Properties"] + assert out["Resources"]["Image"]["Properties"]["Code"] == {"ImageUri": "x"} + assert names["Layer"] == "Layer" + + +def test_condition_used_only_in_fn_if_and_nothing_to_remove(): + template = { + "Conditions": {"CDKMetadataAvailable": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Queue": { + "Type": "AWS::SQS::Queue", + "Properties": {"DelaySeconds": {"Fn::If": ["CDKMetadataAvailable", 1, 2]}}, + "Metadata": meta("S/Queue/Resource"), + } + }, + } + out, names, hints = prepare_cdk(template, []) + assert "CDKMetadataAvailable" in out["Conditions"] + assert names == {"Queue": "Queue"} and hints == {} diff --git a/services/converter-api/tests/test_cfn_compute.py b/services/converter-api/tests/test_cfn_compute.py new file mode 100644 index 0000000..ab7acac --- /dev/null +++ b/services/converter-api/tests/test_cfn_compute.py @@ -0,0 +1,820 @@ +"""Lambda, EC2 and ECS mappings (converters/cfn/resources/compute.py).""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest +import yaml + +from converters.cfn.convert import Converter +from converters.cfn.parse import load_template +from converters.cfn.pipeline import convert_template +from converters.cfn.resources.apigateway import method_path +from converters.cfn.resources.compute import ContainerDefinitions, LambdaCode + +FIXTURE = Path(__file__).parent / "fixtures" / "cfn" / "compute.yaml" + + +def convert(resources: dict, extra: dict | None = None) -> tuple[str, list[str]]: + template = {"Resources": resources} + template.update(extra or {}) + result = convert_template(yaml.safe_dump(template), stack_name="demo") + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + return main, result["notes"] + + +def with_properties(resource: dict, extra: dict) -> dict: + """A copy of `resource` with `extra` added to its properties.""" + properties = dict(resource["Properties"]) + properties.update(extra) + return dict(resource, Properties=properties) + + +def with_hints(resources: dict, hints: dict) -> tuple[str, bool]: + template = load_template(yaml.safe_dump({"Resources": resources})) + converter = Converter(template, hints=hints) + result = converter.run("single") + return result["files"][0]["content"], converter.uses_archive + + +def test_fixture_converts_everything(): + result = convert_template(FIXTURE.read_text(), stack_name="demo") + assert result["summary"]["unsupported"] == 0 + assert not [n for n in result["notes"] if "was not converted" in n] + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + assert 'data "archive_file" "handler_code"' in main + assert 'filename = "app.py"' in main + assert "publish = true" in main + assert 'resource "terraform_data" "version_"' in main + assert "root_block_device" in main and "ephemeral_block_device" in main + assert "assign_public_ip = false" in main + assert "containerPort = 80" in main and "essential = true" in main + assert '"com.example.Team" = "platform"' in main + assert "aws_ecs_cluster_capacity_providers" in main + # Review regressions: defaults, conditional items and string coercion. + worker = main.split('resource "aws_ecs_service" "worker"')[1].split("\n}\n")[0] + agent = main.split('resource "aws_ecs_service" "agent"')[1].split("\n}\n")[0] + assert re.search(r"desired_count += 1", worker) and "desired_count" not in agent + assert re.search(r'no_device += "true"', main) + assert 'dynamic "ebs_block_device"' in main and 'dynamic "routing_config"' in main + assert 'value = "8080"' in main and 'value = "false"' in main and "size = 64" in main + assert "item if item != null" in main + + +FUNCTION = {"Type": "AWS::Lambda::Function", "Properties": {"Role": "arn:role", "Runtime": "x"}} + + +@pytest.mark.parametrize( + ("handler", "runtime", "expected"), + [ + ("app.main", "python3.12", "app.py"), + ("index.handler", "nodejs20.x", "index.js"), + ("lambda_function.handler", "ruby3.3", "lambda_function.rb"), + ("plain", None, "index.py"), + (None, "java21", "index.py"), + ], +) +def test_inline_filename(handler, runtime, expected): + assert LambdaCode.inline_filename(handler, runtime) == expected + + +@pytest.mark.parametrize( + ("path", "expected"), + [ + ("./src", 'source_dir = "${path.module}/src"'), + ("functions/api", 'source_dir = "${path.module}/functions/api"'), + ], +) +def test_code_path_directory_is_zipped(path, expected): + main, archive = with_hints( + {"Fn": with_properties(FUNCTION, {"Code": {"S3Bucket": "x"}})}, + {"Fn": {"code_path": path}}, + ) + assert archive + assert expected in main + assert "filename = data.archive_file.fn_code.output_path" in main + assert "s3_bucket" not in main + + +@pytest.mark.parametrize("path", ["build/app.zip", "target/app.JAR"]) +def test_code_path_archive_is_used_as_is(path): + main, archive = with_hints({"Fn": FUNCTION}, {"Fn": {"code_path": path}}) + assert not archive + assert f'filename = "${{path.module}}/{path}"' in main + assert f'filebase64sha256("${{path.module}}/{path}")' in main + + +def test_layer_code_path_and_generated_name(): + main, archive = with_hints( + {"Layer": {"Type": "AWS::Lambda::LayerVersion", "Properties": {}}}, + {"Layer": {"code_path": "layer"}}, + ) + assert archive + assert 'layer_name = "${var.stack_name}-Layer"' in main + + +def test_function_without_code_and_image_with_explicit_package_type(): + main, notes = convert( + { + "NoCode": FUNCTION, + "Image": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Role": "r", + "PackageType": "Image", + "Code": {"ImageUri": "repo:1", "SourceKMSKeyArn": "k"}, + "LoggingConfig": {"LogGroup": "g"}, + }, + }, + } + ) + assert len(re.findall(r'package_type += "Image"', main)) == 1 + assert 'source_kms_key_arn = "k"' in main + assert 'log_format = "Text"' in main + assert any("NoCode had no FunctionName" in n for n in notes) + + +def test_unconverted_code_property_is_reported(): + _, notes = convert({"Fn": with_properties(FUNCTION, {"Code": {"Odd": 1}})}) + assert any("'Fn.Code.Odd' was not converted" in n for n in notes) + + +def test_versions_of_other_functions_do_not_publish(): + main, notes = convert( + { + "A": FUNCTION, + "B": FUNCTION, + "Queue": {"Type": "AWS::SQS::Queue"}, + "VersionOfB": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": {"Fn::GetAtt": ["B", "Arn"]}}, + }, + "NotAFunction": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": {"Ref": "Queue"}}, + }, + "Computed": { + "Type": "AWS::Lambda::Version", + "Properties": { + "FunctionName": {"Fn::Sub": "fn-${AWS::Region}"}, + "ProvisionedConcurrencyConfig": {"ProvisionedConcurrentExecutions": 3}, + }, + }, + "External": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": "arn:aws:lambda:us-east-1:1:function:x"}, + }, + } + ) + assert main.count("publish") == 1 + assert "aws_lambda_function.b.qualified_arn" in main + assert 'version = "$LATEST"' in main + assert "qualifier = terraform_data.computed.output.version" in main + assert sum("belongs to a function outside this template" in n for n in notes) == 3 + + +def test_event_source_mapping_timestamp_passthrough_and_tags(): + main, _ = convert( + { + "Map": { + "Type": "AWS::Lambda::EventSourceMapping", + "Properties": { + "FunctionName": "fn", + "StartingPositionTimestamp": "2026-01-01T00:00:00Z", + "Queues": "q", + "MetricsConfig": {"Metrics": ["EventCount"]}, + "Tags": [{"Key": "a", "Value": "b"}], + }, + } + } + ) + assert 'starting_position_timestamp = "2026-01-01T00:00:00Z"' in main + assert 'queues = ["q"]' in main + assert 'metrics = ["EventCount"]' in main + + +def test_alias_with_computed_version_weight(): + main, _ = convert( + { + "Fn": FUNCTION, + "Alias": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "Name": "live", + "FunctionName": {"Ref": "Fn"}, + "FunctionVersion": "$LATEST", + "RoutingConfig": { + "AdditionalVersionWeights": [ + {"FunctionVersion": {"Ref": "AWS::Region"}, "FunctionWeight": 0.5} + ] + }, + }, + }, + } + ) + assert "(data.aws_region.current.region) = 0.5" in main + + +def test_instance_devices_interfaces_and_user_data(): + main, notes = convert( + { + "Vm": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": "ami-1", + "UserData": {"Fn::Sub": "x"}, + "BlockDeviceMappings": [ + {"DeviceName": "/dev/sdc", "NoDevice": {}}, + {"DeviceName": "/dev/sdd"}, + {"DeviceName": "/dev/sde", "Ebs": {"SnapshotId": "snap-1"}, "Odd": 1}, + ], + "NetworkInterfaces": [{"DeviceIndex": 1, "SubnetId": "s"}], + }, + }, + "Pair": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": "ami-1", + "NetworkInterfaces": [{"DeviceIndex": 0}, {"DeviceIndex": 1}], + }, + }, + "Attached": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": "ami-1", + "NetworkInterfaces": [{"NetworkInterfaceId": "eni-1", "DeviceIndex": 0}], + }, + }, + "Odd": { + "Type": "AWS::EC2::Instance", + "Properties": {"ImageId": "ami-1", "NetworkInterfaces": ["eni"]}, + }, + } + ) + assert "no_device = true" in main + assert 'snapshot_id = "snap-1"' in main + assert 'user_data_base64 = "x"' in main + assert any("'Vm.BlockDeviceMappings.Odd' was not converted" in n for n in notes) + for name in ("Vm", "Pair", "Attached", "Odd"): + assert any(f"'{name}.NetworkInterfaces' was not converted" in n for n in notes) + + +def test_launch_template_without_data(): + main, _ = convert({"Lt": {"Type": "AWS::EC2::LaunchTemplate", "Properties": {}}}) + assert 'resource "aws_launch_template" "lt" {}' in main + + +def test_cluster_variants(): + main, _ = convert( + { + "Plain": {"Type": "AWS::ECS::Cluster"}, + "Strategy": { + "Type": "AWS::ECS::Cluster", + "Properties": { + "DefaultCapacityProviderStrategy": [{"CapacityProvider": "FARGATE"}], + "Configuration": {"ManagedStorageConfiguration": {"KmsKeyId": "k"}}, + }, + }, + } + ) + assert 'name = "${var.stack_name}-Plain"' in main + assert "capacity_providers" not in main.split("strategy_capacity_providers")[1] + assert 'kms_key_id = "k"' in main + + +def test_ecs_json_keeps_maps_intrinsics_and_types_values(): + value = [ + { + "Name": "app", + "Memory": "512", + "Cpu": "half", + "ReadonlyRootFilesystem": "TRUE", + "Privileged": "maybe", + "Image": {"Fn::Sub": "${Repo}:latest"}, + "DockerLabels": {"KeepMe": "x"}, + "LogConfiguration": {"Options": {"AwsLogs-Group": "g"}}, + } + ] + assert ContainerDefinitions().convert(value) == [ + { + "name": "app", + "memory": 512, + "cpu": "half", + "readonlyRootFilesystem": True, + "privileged": "maybe", + "image": {"Fn::Sub": "${Repo}:latest"}, + "dockerLabels": {"KeepMe": "x"}, + "logConfiguration": {"options": {"AwsLogs-Group": "g"}}, + } + ] + + +def test_task_definition_volumes_and_generated_family(): + main, _ = convert( + { + "Task": { + "Type": "AWS::ECS::TaskDefinition", + "Properties": { + "Volumes": [ + {"Name": "host", "Host": {"SourcePath": "/var/log"}}, + { + "Name": "docker", + "DockerVolumeConfiguration": { + "Autoprovision": True, + "Driver": "local", + "DriverOpts": {"type": "tmpfs"}, + }, + }, + ], + "PlacementConstraints": [{"Type": "memberOf", "Expression": "x"}], + }, + } + } + ) + assert 'family = "${var.stack_name}-Task"' in main + assert 'host_path = "/var/log"' in main + assert "autoprovision = true" in main + assert "container_definitions" not in main + + +def test_service_minimal_and_computed_public_ip(): + main, _ = convert( + { + "Plain": { + "Type": "AWS::ECS::Service", + "Properties": { + "Cluster": "c", + "NetworkConfiguration": {"AwsvpcConfiguration": {"Subnets": ["s"]}}, + }, + }, + "Svc": { + "Type": "AWS::ECS::Service", + "Properties": { + "ServiceName": "svc", + "NetworkConfiguration": { + "AwsvpcConfiguration": { + "Subnets": ["s"], + "AssignPublicIp": {"Fn::Sub": "${AWS::Region}"}, + } + }, + "CapacityProviderStrategy": [{"CapacityProvider": "FARGATE_SPOT", "Weight": 2}], + "PlacementStrategies": [{"Type": "spread", "Field": "attribute:ecs.az"}], + "ServiceRegistries": [{"RegistryArn": "arn", "Port": 80}], + "DeploymentConfiguration": { + "Alarms": {"AlarmNames": ["a"], "Enable": True, "Rollback": False} + }, + }, + }, + } + ) + assert 'name = "${var.stack_name}-Plain"' in main + assert main.count("desired_count = 1") == 2 + assert 'assign_public_ip = data.aws_region.current.region == "ENABLED"' in main + assert 'capacity_provider = "FARGATE_SPOT"' in main + assert 'field = "attribute:ecs.az"' in main + assert 'alarm_names = ["a"]' in main + + +# --- regression tests for the review findings ------------------------------------------- + +CONDITION = { + "Parameters": {"Env": {"Type": "String"}}, + "Conditions": {"On": {"Fn::Equals": [{"Ref": "Env"}, "on"]}}, +} +NO = {"Ref": "AWS::NoValue"} + + +def optional(value): + return {"Fn::If": ["On", value, NO]} + + +SERVICE = {"Type": "AWS::ECS::Service", "Properties": {"ServiceName": "s", "Cluster": "c"}} + + +def test_service_desired_count_defaults_to_one_like_cloudformation(): + main, _ = convert( + { + "Replica": SERVICE, + "Daemon": with_properties(SERVICE, {"SchedulingStrategy": "daemon"}), + "Explicit": with_properties(SERVICE, {"DesiredCount": 0}), + "Chosen": with_properties( + SERVICE, {"SchedulingStrategy": {"Fn::If": ["On", "DAEMON", "REPLICA"]}} + ), + "NoValue": with_properties(SERVICE, {"SchedulingStrategy": NO}), + }, + CONDITION, + ) + blocks = { + m.group(1): m.group(2) + for m in re.finditer(r'"aws_ecs_service" "(\w+)" \{(.*?)\n\}', main, re.S) + } + assert re.search(r"desired_count += 1", blocks["replica"]) + assert re.search(r"desired_count += 1", blocks["no_value"]) + assert "desired_count" not in blocks["daemon"] + assert re.search(r"desired_count += 0", blocks["explicit"]) + assert ( + 'desired_count = (local.on ? "DAEMON" : "REPLICA") == "DAEMON" ? null : 1' + in blocks["chosen"] + ) + + +def test_computed_assign_public_ip_is_parenthesised(): + main, _ = convert( + { + "Svc": with_properties( + SERVICE, + { + "NetworkConfiguration": { + "AwsvpcConfiguration": { + "Subnets": ["s"], + "AssignPublicIp": {"Fn::If": ["On", "ENABLED", "DISABLED"]}, + } + }, + }, + ) + }, + CONDITION, + ) + assert 'assign_public_ip = (local.on ? "ENABLED" : "DISABLED") == "ENABLED"' in main + + +def test_launch_template_no_device_is_never_empty(): + main, _ = convert( + { + "Lt": { + "Type": "AWS::EC2::LaunchTemplate", + "Properties": { + "LaunchTemplateData": { + "BlockDeviceMappings": [ + {"DeviceName": "/dev/sdb", "NoDevice": ""}, + {"DeviceName": "/dev/sdc", "NoDevice": "yes"}, + {"DeviceName": "/dev/sdd", "NoDevice": {"Ref": "Env"}}, + ] + } + }, + } + }, + CONDITION, + ) + assert 'no_device = "true"' in main + assert 'no_device = "yes"' in main + assert 'no_device = coalesce(var.env, "true")' in main + + +def test_root_method_path_is_not_every_resource(): + assert method_path("/", "GET") == "~1/GET" + + +def test_inline_code_using_cfn_response_is_noted(): + code = {"ZipFile": {"Fn::Sub": "import cfnresponse\n"}} + _, notes = convert({"Fn": with_properties(FUNCTION, {"Code": code})}) + assert any("cfn-response module" in n for n in notes) + plain = {"ZipFile": "def handler(e, c): pass\n"} + _, notes = convert({"Fn": with_properties(FUNCTION, {"Code": plain})}) + assert not any("cfn-response" in n for n in notes) + + +def test_ref_of_function_url_is_the_function_arn(): + result = convert_template( + yaml.safe_dump( + { + "Resources": { + "Url": { + "Type": "AWS::Lambda::Url", + "Properties": {"TargetFunctionArn": "arn:fn", "AuthType": "NONE"}, + } + }, + "Outputs": {"U": {"Value": {"Ref": "Url"}}}, + } + ), + stack_name="demo", + ) + outputs = next(f["content"] for f in result["files"] if f["path"] == "outputs.tf") + assert "aws_lambda_function_url.url.function_arn" in outputs + + +def test_primary_interface_kept_on_termination_is_noted(): + main, notes = convert( + { + "Vm": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": "ami-1", + "NetworkInterfaces": [ + {"DeviceIndex": 0, "SubnetId": "s", "DeleteOnTermination": "false"} + ], + }, + }, + "Default": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": "ami-1", + "NetworkInterfaces": [ + {"DeviceIndex": 0, "SubnetId": "s", "DeleteOnTermination": "True"} + ], + }, + }, + } + ) + assert '# DeleteOnTermination was not converted: "false"' in main + assert sum("primary network interface" in n for n in notes) == 1 + + +def test_container_definitions_types_strings_and_conditional_containers(): + value = [ + { + "Name": "app", + "Environment": [ + {"Name": "PORT", "Value": 8080}, + {"Name": "DEBUG", "Value": False}, + {"Name": "RATIO", "Value": 0.5}, + {"Fn::If": ["On", {"Name": "X", "Value": 1}, NO]}, + "odd", + {"Name": "NOVALUE"}, + ], + "DockerLabels": {"version": 2}, + "LogConfiguration": {"Options": {"awslogs-create-group": True}}, + "LinuxParameters": {"Tmpfs": [{"ContainerPath": "/scratch", "Size": "64"}]}, + "Memory": {"Fn::If": ["On", "512", "256"]}, + }, + {"Fn::If": ["On", {"Name": "sidecar", "Essential": "false"}, NO]}, + {"Fn::If": ["On"]}, + {"Ref": "Containers"}, + {"Environment": "odd", "DockerLabels": "odd"}, + ] + assert ContainerDefinitions().convert(value) == [ + { + "name": "app", + "environment": [ + {"name": "PORT", "value": "8080"}, + {"name": "DEBUG", "value": "false"}, + {"name": "RATIO", "value": "0.5"}, + {"Fn::If": ["On", {"name": "X", "value": "1"}, NO]}, + "odd", + {"name": "NOVALUE"}, + ], + "dockerLabels": {"version": "2"}, + "logConfiguration": {"options": {"awslogs-create-group": "true"}}, + "linuxParameters": {"tmpfs": [{"containerPath": "/scratch", "size": 64}]}, + "memory": {"Fn::If": ["On", 512, 256]}, + }, + {"Fn::If": ["On", {"name": "sidecar", "essential": False}, NO]}, + {"Fn::If": ["On"]}, + {"Ref": "Containers"}, + {"environment": "odd", "dockerLabels": "odd"}, + ] + + +def test_conditional_container_is_filtered_out_of_the_list(): + main, _ = convert( + { + "Task": { + "Type": "AWS::ECS::TaskDefinition", + "Properties": { + "Family": "f", + "ContainerDefinitions": [ + {"Name": "app", "Image": "i"}, + optional({"Name": "sidecar", "Image": "busybox", "Memory": "64"}), + ], + "Volumes": [ + {"Name": "logs", "Host": optional({"SourcePath": "/var/log"})}, + {"Name": "odd", "Host": {"Fn::If": ["On", {"SourcePath": "/a"}, {}]}}, + ], + }, + } + }, + CONDITION, + ) + assert "item if item != null" in main + assert re.search(r"local\.on \? \{ [^}]*memory = 64[^}]* \} : null", main) + assert 'host_path = local.on ? "/var/log" : null' in main + assert "# Host was not converted" in main + + +def test_namespace_name_is_noted(): + main, notes = convert( + { + "Name": { + "Type": "AWS::ECS::Cluster", + "Properties": {"ClusterName": "a", "ServiceConnectDefaults": {"Namespace": "ns"}}, + }, + "Arn": { + "Type": "AWS::ECS::Cluster", + "Properties": { + "ClusterName": "b", + "ServiceConnectDefaults": {"Namespace": "arn:aws:servicediscovery:ns"}, + }, + }, + } + ) + assert 'namespace = "ns"' in main + assert sum("Terraform needs the namespace ARN" in n for n in notes) == 1 + + +def test_conditional_alias_routing_and_concurrency(): + main, notes = convert( + { + "Fn": FUNCTION, + "Alias": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "Name": "live", + "FunctionName": {"Ref": "Fn"}, + "FunctionVersion": "1", + "RoutingConfig": optional( + { + "AdditionalVersionWeights": [ + {"FunctionVersion": "2", "FunctionWeight": 0.5}, + {"Ref": "Weight"}, + ] + } + ), + "ProvisionedConcurrencyConfig": optional( + {"ProvisionedConcurrentExecutions": 1} + ), + }, + }, + "Computed": { + "Type": "AWS::Lambda::Alias", + "Properties": { + "Name": "c", + "FunctionName": {"Ref": "Fn"}, + "FunctionVersion": "1", + "RoutingConfig": {"AdditionalVersionWeights": {"Ref": "Weights"}}, + "ProvisionedConcurrencyConfig": {"Fn::If": ["On", {"A": 1}, {"B": 2}]}, + }, + }, + }, + { + "Parameters": { + "Env": {"Type": "String"}, + "Weight": {"Type": "String"}, + "Weights": {"Type": "String"}, + }, + "Conditions": CONDITION["Conditions"], + }, + ) + assert 'dynamic "routing_config" {\n for_each = local.on ? [1] : []' in main + assert '"2" = 0.5' in main + assert "count = local.on ? 1 : 0" in main + assert "additional_version_weights = {}" in main + assert "# AdditionalVersionWeights was not converted" in main + assert "# ProvisionedConcurrencyConfig was not converted" in main + + +def test_conditional_and_computed_block_device_mappings(): + main, notes = convert( + { + "Vm": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": "ami-1", + "BlockDeviceMappings": [ + optional({"DeviceName": "/dev/sdf", "Ebs": {"VolumeSize": 10}}), + {"Fn::If": ["On", {"DeviceName": "/dev/sdg"}, {"DeviceName": "/dev/sdh"}]}, + ], + }, + }, + "Whole": { + "Type": "AWS::EC2::Instance", + "Properties": {"ImageId": "ami-1", "BlockDeviceMappings": optional([])}, + }, + }, + CONDITION, + ) + assert 'dynamic "ebs_block_device" {\n for_each = local.on ? [1] : []' in main + assert 'device_name = "/dev/sdf"' in main + assert "# BlockDeviceMappings was not converted" in main + assert "ebs_block_device {\n device_name = null" not in main + assert any("'Whole.BlockDeviceMappings' is computed" in n for n in notes) + + +def test_computed_launch_template_tag_specifications_do_not_crash(): + main, notes = convert( + { + "Whole": { + "Type": "AWS::EC2::LaunchTemplate", + "Properties": { + "TagSpecifications": optional([{"ResourceType": "launch-template"}]) + }, + }, + "Items": { + "Type": "AWS::EC2::LaunchTemplate", + "Properties": { + "TagSpecifications": [ + optional({"ResourceType": "launch-template"}), + {"ResourceType": "launch-template", "Tags": {"Ref": "Tags"}}, + ] + }, + }, + }, + { + "Parameters": {"Env": {"Type": "String"}, "Tags": {"Type": "String"}}, + "Conditions": CONDITION["Conditions"], + }, + ) + assert main.count("# TagSpecifications") == 3 + assert "# TagSpecifications.Tags was not converted" in main + assert len([n for n in notes if "is computed by a function" in n]) == 3 + + +EVIL = 'x" ${file("/etc/passwd")} y' + + +def test_template_text_cannot_inject_hcl(): + main, _ = convert( + { + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": { + "FunctionName": EVIL, + "Role": EVIL, + "Handler": EVIL, + "Runtime": "python3.12", + "Code": {"ZipFile": EVIL}, + }, + }, + "Vm": { + "Type": "AWS::EC2::Instance", + "Properties": { + "ImageId": EVIL, + "BlockDeviceMappings": [{"DeviceName": EVIL, "Ebs": {"VolumeSize": 1}}], + "NetworkInterfaces": [ + {"DeviceIndex": 0, "SubnetId": EVIL, "DeleteOnTermination": EVIL} + ], + }, + }, + "Task": { + "Type": "AWS::ECS::TaskDefinition", + "Properties": { + "Family": EVIL, + "ContainerDefinitions": [ + {"Name": EVIL, "Environment": [{"Name": EVIL, "Value": EVIL}]} + ], + "Volumes": [{"Name": EVIL, "Host": {"SourcePath": EVIL}}], + }, + }, + "Lt": { + "Type": "AWS::EC2::LaunchTemplate", + "Properties": { + "LaunchTemplateData": { + "BlockDeviceMappings": [{"DeviceName": EVIL, "NoDevice": EVIL}] + } + }, + }, + "Svc": with_properties( + SERVICE, + { + "SchedulingStrategy": EVIL, + "NetworkConfiguration": { + "AwsvpcConfiguration": {"Subnets": [EVIL], "AssignPublicIp": EVIL} + }, + }, + ), + "Cl": { + "Type": "AWS::ECS::Cluster", + "Properties": {"ClusterName": EVIL, "ServiceConnectDefaults": {"Namespace": EVIL}}, + }, + } + ) + assert_no_injection(main) + + +def assert_no_injection(main: str) -> None: + """EVIL only ever appears escaped outside comments (which are one line of JSON text).""" + code = "\n".join(line for line in main.splitlines() if not line.lstrip().startswith("#")) + assert 'file("' not in code + assert not re.search(r"(? dict: + """Convert a template with options given as a dict (provider, layout, stack_name, + include_imports).""" + text = template if isinstance(template, str) else yaml.safe_dump(template, sort_keys=False) + options = options or {} + converter = TemplateConverter( + options.get("provider", "aws"), + options.get("layout", "files"), + options.get("stack_name"), + options.get("include_imports", False), + ) + return converter.convert(text) + + +def files(template: dict | str, options: dict | None = None) -> dict[str, str]: + return {f["path"]: f["content"] for f in run(template, options)["files"]} + + +def squeeze(text: str) -> str: + """Alignment padding collapsed, so tests don't depend on neighbouring attribute names.""" + return re.sub(r" +", " ", text) + + +def notes(template: dict | str, options: dict | None = None) -> list[str]: + return run(template, options)["notes"] + + +def expression(value, template: dict | None = None) -> str: + """One CloudFormation value, rendered, as the value of an output.""" + template = template or {} + template.setdefault("Resources", dict(BUCKET)) + template["Outputs"] = {"Out": {"Value": value}} + out = files(template)["outputs.tf"] + return out.split("value = ", 1)[1].rsplit("\n}", 1)[0] + + +# --- parsing --------------------------------------------------------------------------- + + +def test_yaml_short_forms_become_long_forms(): + template = load_template( + "Resources:\n" + " B:\n" + " Type: AWS::S3::Bucket\n" + " Properties:\n" + " BucketName: !Sub '${AWS::StackName}-x'\n" + " Tags:\n" + " - Key: a\n" + " Value: !GetAtt Other.Arn.Deep\n" + " - Key: b\n" + " Value: !Ref Thing\n" + " - Key: c\n" + " Value: !Join [',', [a, b]]\n" + " - Key: d\n" + " Value: !If [Cond, {x: 1}, !Ref AWS::NoValue]\n" + " - Key: e\n" + " Value: !Condition C\n" + ) + props = template["Resources"]["B"]["Properties"] + assert props["BucketName"] == {"Fn::Sub": "${AWS::StackName}-x"} + assert props["Tags"][0]["Value"] == {"Fn::GetAtt": ["Other", "Arn.Deep"]} + assert props["Tags"][1]["Value"] == {"Ref": "Thing"} + assert props["Tags"][2]["Value"] == {"Fn::Join": [",", ["a", "b"]]} + assert props["Tags"][3]["Value"] == {"Fn::If": ["Cond", {"x": 1}, {"Ref": "AWS::NoValue"}]} + assert props["Tags"][4]["Value"] == {"Condition": "C"} + + +def test_yaml_scalars_follow_yaml_1_2(): + template = load_template( + "AWSTemplateFormatVersion: 2010-09-09\n" + "Resources:\n" + " B:\n" + " Type: AWS::S3::Bucket\n" + " Properties: {A: on, B: 0755, C: 12, D: 1.5, E: true, F: ~, G: FALSE, H: '1'}\n" + ) + assert template["AWSTemplateFormatVersion"] == "2010-09-09" + assert template["Resources"]["B"]["Properties"] == { + "A": "on", + "B": "0755", + "C": 12, + "D": 1.5, + "E": True, + "F": None, + "G": False, + "H": "1", + } + + +def test_json_templates_and_bom(): + template = load_template("\ufeff" + json.dumps({"Resources": BUCKET})) + assert template["Resources"]["Bucket"]["Type"] == "AWS::S3::Bucket" + + +@pytest.mark.parametrize( + ("text", "message", "line"), + [ + ("", "Input is empty", None), + (" ", "Input is empty", None), + ('{"Resources": ', "Invalid JSON", 1), + ("\n\n{\n bad", "Invalid JSON", 4), + ("Resources: [1\n", "Invalid YAML", 2), + ("Resources:\n B: !Unknown x\n", "Unknown YAML tag '!Unknown'", 2), + ("- 1\n- 2\n", "top level must be a mapping", None), + ("Description: x\n", "no 'Resources' defined", None), + ("Resources: [1]\n", "'Resources' must be a mapping", None), + ("Resources:\n B: 1\n", "resource 'B' must be a mapping", None), + ("Resources:\n B: {Properties: {}}\n", "resource 'B' has no 'Type'", None), + ("Resources:\n B: {Type: X, Properties: [1]}\n", "'Properties' of 'B' must be", None), + ("Resources: {B: {Type: X}}\nParameters: [1]\n", "'Parameters' must be a mapping", None), + ("Resources: {B: {Type: X}}\nParameters: {P: {Default: 1}}\n", "needs a 'Type'", None), + ("Resources: {B: {Type: X}}\nOutputs: {O: {Description: x}}\n", "needs a 'Value'", None), + ], +) +def test_invalid_templates(text, message, line): + with pytest.raises(CfnError) as error: + load_template(text) + assert message in error.value.message + assert error.value.line == line + + +def test_size_and_depth_limits(): + with pytest.raises(CfnError, match="longer than"): + load_template("a" * (MAX_TEMPLATE_CHARS + 1)) + with pytest.raises(CfnError, match="nested too deeply"): + load_template("Resources: " + "[" * 150 + "]" * 150) + with pytest.raises(CfnError, match="nested too deeply"): + load_template('{"Resources": ' + "[" * 150 + "]" * 150 + "}") + with pytest.raises(CfnError, match="nested too deeply"): + load_template('{"Resources": ' + "[" * 100_000 + "]" * 100_000 + "}") + values = ",".join("0" * 100_001) + with pytest.raises(CfnError, match="Template too large"): + load_template('{"Resources": {"B": {"Type": "X", "Properties": {"V": [' + values + "]}}}}") + with pytest.raises(CfnError, match="more than"): + load_template("Resources: {B: {Type: X, Properties: {V: [" + values + "]}}}") + + +def test_alias_bombs_are_rejected(): + bomb = "a: &a [x, x, x, x, x, x, x, x, x, x]\n" + for level in range(1, 8): + previous = "a" if level == 1 else f"a{level - 1}" + bomb += f"a{level}: &a{level} [*{previous}, *{previous}, *{previous}, *{previous}]\n" + with pytest.raises(CfnError, match="Template too large"): + load_template(bomb + "Resources: {B: {Type: X, Properties: {V: *a7}}}\n") + + +def test_detect_source(): + assert detect_source({"Resources": BUCKET}) == "cloudformation" + assert ( + detect_source({"Transform": ["AWS::Serverless-2016-10-31"], "Resources": BUCKET}) == "sam" + ) + assert detect_source({"Resources": {"M": {"Type": "AWS::CDK::Metadata"}}}) == "cdk" + cdk = {"Resources": {"B": {"Type": "X", "Metadata": {"aws:cdk:path": "S/B/Resource"}}}} + assert detect_source(cdk) == "cdk" + + +# --- naming ---------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("name", "expected"), + [ + ("BucketName", "bucket_name"), + ("VPCId", "vpc_id"), + ("DBInstanceClass", "db_instance_class"), + ("Ipv6CidrBlock", "ipv_6_cidr_block"), + ("S3Bucket", "s3_bucket"), + ("CertificateS3BucketName", "certificate_s3_bucket_name"), + ("EC2InstanceType", "ec2_instance_type"), + ("CloudWatchRoleArn", "cloudwatch_role_arn"), + ("BasePathMappingV2", "base_path_mapping_v2"), + ("FSxLustreConfig", "fsx_lustre_config"), + ], +) +def test_snake_matches_awscc(name, expected): + assert snake(name) == expected + + +def test_identifier_and_unique_names(): + assert identifier("MyBucket") == "my_bucket" + assert identifier("1stQueue") == "r_1st_queue" + assert identifier("S3Endpoint") == "s3_endpoint" + assert identifier("PublicSubnet1A") == "public_subnet1_a" + assert identifier("MyVPC") == "my_vpc" + assert identifier("DBInstance") == "db_instance" + assert identifier("Count") == "count_" + assert identifier("count") == "count_" + assert identifier("Version") == "version_" + assert identifier("é") == "this" + assert identifier("--", fallback="x") == "x" + assert len(identifier("A" * 200)) <= 64 + names = UniqueNames() + assert [names.take("a"), names.take("a"), names.take("a")] == ["a", "a_2", "a_3"] + names.reserve("b") + assert names.take("b") == "b_2" + + +def test_awscc_type_names(): + assert awscc_type("AWS::S3::Bucket") == "awscc_s3_bucket" + assert awscc_type("AWS::EC2::VPCEndpoint") == "awscc_ec2_vpc_endpoint" + assert ( + awscc_type("AWS::CloudFront::CloudFrontOriginAccessIdentity") + == "awscc_cloudfront_cloudfront_origin_access_identity" + ) + assert awscc_type("AWS::Not::AThing") is None + + +# --- HCL rendering ---------------------------------------------------------------------- + + +def test_quote_escapes_interpolation_and_control_characters(): + assert hcl.quote('a "b" \\ ${x} %{y}\n\t\r') == '"a \\"b\\" \\\\ $${x} %%{y}\\n\\t\\r"' + + +def test_render_values(): + assert hcl.render(None) == "null" + assert hcl.render(True) == "true" + assert hcl.render(3.0) == "3" + assert hcl.render(2.5) == "2.5" + assert hcl.render(float("inf")) == '"inf"' + assert hcl.render(1e20) == "1e+20" + assert hcl.render([]) == "[]" + assert hcl.render({}) == "{}" + assert hcl.render(["a", 1]) == '["a", 1]' + assert hcl.render([{"a": 1}]) == "[\n {\n a = 1\n },\n]" + assert hcl.render(["x" * 90]) == '[\n "' + "x" * 90 + '",\n]' + assert hcl.render({"aws:Key": 1, "true": 2, Raw("var.k"): 3}) == ( + '{\n "aws:Key" = 1\n "true" = 2\n (var.k) = 3\n}' + ) + + assert hcl.render(datetime.date(2024, 1, 2)) == '"2024-01-02"' + + +def test_inline_rendering(): + value = Call("f", [{"a": 1, "b": Comment("x")}, {}, "s"]) + assert hcl.inline(value) == 'f([{ a = 1 }, {}, "s"])' + + +def test_blocks_align_like_terraform_fmt(): + block = Block( + "resource", + ["t", "n"], + [ + Attr("a", 1), + Attr("bbbb", 2), + Attr("obj", {"k": 1, "kkk": 2}), + Attr("c", 3), + Comment("note\nsecond line"), + Attr("dd", 4), + BLANK, + BLANK, + Block("inner", [], []), + BLANK, + ], + ) + assert hcl.render_block(block) == ( + 'resource "t" "n" {\n' + " a = 1\n" + " bbbb = 2\n" + " obj = {\n" + " k = 1\n" + " kkk = 2\n" + " }\n" + " c = 3\n" + " # note\n" + " # second line\n" + " dd = 4\n" + "\n" + " inner {}\n" + "}" + ) + + +def test_render_file_keeps_comments_above_blocks(): + text = hcl.render_file([Block("a", [], []), Comment("about b"), Block("b", [], [])]) + assert text == "a {}\n\n# about b\nb {}\n" + + +# --- expressions ------------------------------------------------------------------------ + + +def test_ref_and_pseudo_parameters(): + template = {"Parameters": {"Env": {"Type": "String"}}} + assert expression({"Ref": "Env"}, template) == "var.env" + assert expression({"Ref": "AWS::Region"}) == "data.aws_region.current.region" + assert expression({"Ref": "AWS::AccountId"}) == "data.aws_caller_identity.current.account_id" + assert expression({"Ref": "AWS::Partition"}) == "data.aws_partition.current.partition" + assert expression({"Ref": "AWS::URLSuffix"}) == "data.aws_partition.current.dns_suffix" + assert expression({"Ref": "AWS::StackName"}) == "var.stack_name" + assert expression({"Ref": "AWS::NoValue"}) == "null" + assert expression({"Ref": "AWS::NotificationARNs"}) == "[]" + assert expression({"Ref": "AWS::StackId"}) == "var.stack_name" + assert expression({"Ref": "Bucket"}) == "aws_s3_bucket.bucket.id" + + +def test_pseudo_parameters_add_data_sources(): + main = files({"Resources": BUCKET, "Outputs": {"R": {"Value": {"Ref": "AWS::Region"}}}})[ + "main.tf" + ] + assert main.startswith('data "aws_region" "current" {}') + + +def test_get_att(): + assert expression({"Fn::GetAtt": ["Bucket", "Arn"]}) == "aws_s3_bucket.bucket.arn" + assert expression({"Fn::GetAtt": "Bucket.Arn"}) == "aws_s3_bucket.bucket.arn" + queue = {"Q": {"Type": "AWS::SQS::Queue"}} + unknown = {"Resources": {"Q": {"Type": "AWS::Batch::JobQueue"}}} + assert expression({"Fn::GetAtt": ["Q", "JobQueueArn"]}, unknown) == ( + "awscc_batch_job_queue.q.job_queue_arn" + ) + assert "queue" in expression({"Fn::GetAtt": ["Q", "Arn"]}, {"Resources": queue}) + + +def test_get_att_unknown_attribute_on_a_mapped_type_is_noted(): + template = { + "Resources": BUCKET, + "Outputs": {"O": {"Value": {"Fn::GetAtt": ["Bucket", "DualStackDomainName"]}}}, + } + out = files(template)["outputs.tf"] + assert "aws_s3_bucket.bucket.dual_stack_domain_name" in out + assert any("check that attribute exists" in n for n in notes(template)) + + +def test_get_att_computed_attribute_name(): + template = { + "Parameters": {"A": {"Type": "String"}}, + "Resources": BUCKET, + "Outputs": {"O": {"Value": {"Fn::GetAtt": ["Bucket", {"Ref": "A"}]}}}, + } + assert "value = null" in files(template)["outputs.tf"] + assert any("computed attribute name" in n for n in notes(template)) + + +@pytest.mark.parametrize( + ("value", "message"), + [ + ({"Ref": "Nope"}, "which is no parameter or resource"), + ({"Ref": ["x"]}, "takes the name"), + ({"Fn::GetAtt": ["Nope", "Arn"]}, "unknown resource 'Nope'"), + ({"Fn::GetAtt": ["Bucket"]}, "takes [resource, attribute]"), + ({"Fn::Sub": 1}, "needs a string"), + ({"Fn::Sub": ["a", "b"]}, "takes a string or"), + ({"Fn::Join": ["a"]}, "'Fn::Join' takes a list of 2"), + ({"Fn::Select": [5, ["a"]]}, "out of range"), + ({"Fn::If": ["Nope", 1, 2]}, "Unknown condition 'Nope'"), + ({"Fn::FindInMap": ["Nope", "a", "b"]}, "unknown mapping 'Nope'"), + ({"Fn::And": [{"Condition": "X"}]}, "2 to 10 conditions"), + ({"Fn::Cidr": ["not-a-cidr", 2, 8]}, "is unable to split"), + ], +) +def test_invalid_intrinsics(value, message): + with pytest.raises(CfnError) as error: + expression(value) + assert message in error.value.message + + +def test_sub(): + template = {"Parameters": {"Env": {"Type": "String"}}} + assert expression({"Fn::Sub": "plain"}) == '"plain"' + assert expression({"Fn::Sub": "${Env}"}, template) == "var.env" + assert expression({"Fn::Sub": "${Env}-${Bucket.Arn}"}, template) == ( + '"${var.env}-${aws_s3_bucket.bucket.arn}"' + ) + assert expression({"Fn::Sub": "a-${!Literal}-b"}) == '"a-$${Literal}-b"' + assert expression({"Fn::Sub": ["${X}/${Y}", {"X": "lit", "Y": {"Ref": "Env"}}]}, template) == ( + '"lit/${var.env}"' + ) + assert expression({"Fn::Sub": ["${X}", {"X": "lit"}]}) == '"lit"' + assert expression({"Fn::Sub": "arn:${AWS::Partition}:s3:::x"}) == ( + '"arn:${data.aws_partition.current.partition}:s3:::x"' + ) + + +def test_join_select_split(): + template = {"Parameters": {"L": {"Type": "CommaDelimitedList"}, "E": {"Type": "String"}}} + assert expression({"Fn::Join": ["-", ["a", 1, 2.5]]}) == '"a-1-2.5"' + assert expression({"Fn::Join": ["-", ["a", {"Ref": "E"}, True]]}, template) == ( + '"a-${var.e}-true"' + ) + assert expression({"Fn::Join": [",", {"Ref": "L"}]}, template) == 'join(",", var.l)' + assert expression({"Fn::Join": [",", [{"Fn::Split": [",", {"Ref": "E"}]}]]}, template) == ( + 'join(",", [split(",", var.e)])' + ) + assert expression({"Fn::Join": ["", [{"Fn::Sub": "x"}, "y"]]}) == '"xy"' + assert expression({"Fn::Select": ["1", ["a", "b"]]}) == '"b"' + assert expression({"Fn::Select": [0, {"Ref": "L"}]}, template) == "element(var.l, 0)" + assert expression({"Fn::Split": [",", "a,b"]}) == '["a", "b"]' + assert expression({"Fn::Split": [",", {"Ref": "E"}]}, template) == 'split(",", var.e)' + + +def test_azs_base64_cidr(): + assert expression({"Fn::GetAZs": ""}) == "data.aws_availability_zones.available.names" + assert expression({"Fn::GetAZs": {"Ref": "AWS::Region"}}).endswith(".names") + template = {"Resources": dict(BUCKET), "Outputs": {"O": {"Value": {"Fn::GetAZs": "eu-west-1"}}}} + assert any("another region" in n for n in notes(template)) + assert expression({"Fn::Base64": "x"}) == 'base64encode("x")' + assert expression({"Fn::Cidr": ["10.0.0.0/16", 3, 8]}) == ( + '["10.0.0.0/24", "10.0.1.0/24", "10.0.2.0/24"]' + ) + template = {"Parameters": {"C": {"Type": "String"}}} + assert expression({"Fn::Cidr": [{"Ref": "C"}, 2, 8]}, template) == ( + '[for i in range(2) : cidrsubnet(var.c, (strcontains(var.c, ":") ? 128 : 32) - 8 ' + '- tonumber(split("/", var.c)[1]), i)]' + ) + + +def test_find_in_map_and_conditions(): + template = { + "Parameters": {"Env": {"Type": "String"}, "Count": {"Type": "Number"}}, + "Mappings": {"Sizes": {"dev": {"Mem": 128}}}, + "Conditions": { + "IsDev": {"Fn::Equals": [{"Ref": "Env"}, "dev"]}, + "IsTwo": {"Fn::Equals": [{"Ref": "Count"}, "2"]}, + "IsNum": {"Fn::Equals": [{"Ref": "Env"}, 3]}, + "Both": {"Fn::And": [{"Condition": "IsDev"}, {"Fn::Not": [{"Condition": "IsTwo"}]}]}, + "Either": {"Fn::Or": [{"Condition": "IsDev"}, {"Fn::Equals": ["a", "b"]}]}, + }, + } + assert expression({"Fn::FindInMap": ["Sizes", {"Ref": "Env"}, "Mem"]}, dict(template)) == ( + 'local.sizes[var.env]["Mem"]' + ) + assert expression( + {"Fn::FindInMap": ["Sizes", "x", "Mem", {"DefaultValue": 64}]}, dict(template) + ) == ('lookup(lookup(local.sizes, "x", {}), "Mem", 64)') + assert expression({"Fn::If": ["IsDev", 1, {"Ref": "AWS::NoValue"}]}, dict(template)) == ( + "local.is_dev ? 1 : null" + ) + locals_tf = squeeze(files(dict(template, Resources=BUCKET))["locals.tf"]) + assert 'is_dev = var.env == "dev"' in locals_tf + assert 'is_two = tostring(var.count_) == "2"' in locals_tf + assert 'is_num = var.env == "3"' in locals_tf + assert "both = local.is_dev && !local.is_two" in locals_tf + assert 'either = local.is_dev || ("a" == "b")' in locals_tf + assert "Mem = 128" in locals_tf + + +def test_import_value_becomes_a_variable(): + template = { + "Resources": dict(BUCKET), + "Outputs": {"O": {"Value": {"Fn::ImportValue": "net-VpcId"}}}, + } + out = files(template) + assert "value = var.import_net_vpc_id" in out["outputs.tf"] + assert 'variable "import_net_vpc_id"' in out["variables.tf"] + assert any("Terraform has no stack exports" in n for n in notes(template)) + computed = {"Fn::ImportValue": {"Fn::Sub": "${AWS::StackName}-Vpc"}} + assert expression(computed).startswith("var.import_") + + +def test_language_extensions_and_unsupported_functions(): + assert expression({"Fn::ToJsonString": {"a": 1}}) == "jsonencode({\n a = 1\n })" + assert expression({"Fn::Length": [1, 2]}) == "2" + template = {"Parameters": {"L": {"Type": "CommaDelimitedList"}}} + assert expression({"Fn::Length": {"Ref": "L"}}, template) == "length(var.l)" + assert expression({"Fn::Transform": {"Name": "AWS::Include"}}) == "null" + assert expression({"Fn::Nope": 1}) == "null" + unknown = {"Resources": dict(BUCKET), "Outputs": {"O": {"Value": {"Fn::Nope": 1}}}} + assert any("'Fn::Nope' is not supported" in n for n in notes(unknown)) + + +def test_plain_mappings_and_lists_keep_their_keys(): + assert expression({"Ref": "Bucket", "Other": 1}) == ( + '{\n Ref = "Bucket"\n Other = 1\n }' + ) + + +def test_expressions_nested_too_deeply(): + value: dict = {"Fn::Base64": "x"} + for _ in range(60): + value = {"Fn::Base64": value} + with pytest.raises(CfnError, match="nested too deeply"): + expression(value) + + +def test_expression_objects_from_the_sam_step(): + ctx = Context({"Resources": {}}) + assert ctx.expr(Expression('file("x")')) == Raw('file("x")') + + +# --- parameters ------------------------------------------------------------------------- + + +def test_parameters_become_variables_with_validation(): + template = { + "Metadata": { + "AWS::CloudFormation::Interface": { + "ParameterLabels": {"Size": {"default": "Size of it"}} + } + }, + "Parameters": { + "Env": { + "Type": "String", + "Description": "Where it runs", + "Default": "dev", + "AllowedValues": ["dev", "prod"], + "ConstraintDescription": "pick dev or prod", + }, + "Name": { + "Type": "String", + "AllowedPattern": "[a-z]+", + "MinLength": 1, + "MaxLength": "8", + }, + "Size": {"Type": "Number", "Default": "10", "MinValue": 1, "MaxValue": 100}, + "Ratio": {"Type": "Number", "Default": "0.5"}, + "Bad": {"Type": "Number", "Default": "lots"}, + "Ports": {"Type": "List", "Default": "80, 443"}, + "Subnets": {"Type": "List", "Default": ["a", "b"]}, + "Zones": {"Type": "CommaDelimitedList", "Default": "a,,b", "AllowedValues": ["a"]}, + "Secret": {"Type": "String", "NoEcho": "true"}, + "Flag": {"Type": "String", "Default": True}, + "Ami": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/aws/service/ami", + "Description": "Image", + }, + "Ids": {"Type": "AWS::SSM::Parameter::Value>"}, + "Count": {"Type": "String"}, + }, + "Resources": BUCKET, + "Outputs": { + "A": {"Value": {"Ref": "Ami"}}, + "B": {"Value": {"Ref": "Ids"}}, + "S": {"Value": {"Ref": "Secret"}}, + }, + } + out = {k: squeeze(v) for k, v in files(template).items()} + variables = out["variables.tf"] + assert 'description = "Where it runs"' in variables + assert 'condition = contains(["dev", "prod"], var.env)' in variables + assert 'error_message = "Pick dev or prod."' in variables + assert 'can(regex("^(?:[a-z]+)$", var.name))' in variables + assert "length(var.name) >= 1" in variables and "length(var.name) <= 8" in variables + assert 'description = "Size of it"' in variables + assert "default = 10" in variables and "var.size >= 1" in variables + assert "default = 0.5" in variables + assert 'default = "lots"' in variables + assert "type = list(number)\n default = [80, 443]" in variables + assert 'default = ["a", "b"]' in variables + assert "sensitive = true" in variables + assert 'default = "true"' in variables + assert 'description = "Image (name of the SSM parameter that holds the value)"' in variables + assert 'variable "count_"' in variables + main = out["main.tf"] + assert 'data "aws_ssm_parameter" "ami" {\n name = var.ami\n}' in main + outputs = out["outputs.tf"] + assert "value = data.aws_ssm_parameter.ami.insecure_value" in outputs + assert 'value = split(",", data.aws_ssm_parameter.ids.insecure_value)' in outputs + assert "value = var.secret\n sensitive = true" in outputs + + +def test_stack_name_variable_and_default(): + template = { + "Resources": { + "B": { + "Type": "AWS::S3::Bucket", + "Properties": {"BucketName": {"Ref": "AWS::StackName"}}, + } + } + } + assert 'default = "shop"' in files(template, {"stack_name": "shop"})["variables.tf"] + assert "default" not in files(template)["variables.tf"] + clash = dict(template, Parameters={"StackName": {"Type": "String"}}) + assert 'variable "stack_name_2"' in files(clash)["variables.tf"] + + +# --- resources and their attributes ---------------------------------------------------- + + +def test_resource_attributes(): + template = { + "Conditions": {"On": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "A": {"Type": "AWS::S3::Bucket", "Condition": "On", "DeletionPolicy": "Retain"}, + "B": { + "Type": "AWS::S3::Bucket", + "DependsOn": ["A", "C"], + "DeletionPolicy": "Snapshot", + "UpdateReplacePolicy": "Retain", + "CreationPolicy": {"x": 1}, + "Metadata": {"AWS::CloudFormation::Init": {}}, + }, + "C": {"Type": "Custom::Thing", "Properties": {"ServiceToken": "arn"}}, + }, + "Outputs": {"O": {"Value": {"Fn::GetAtt": ["C", "Result"]}}, "R": {"Value": {"Ref": "C"}}}, + } + out = files(template) + main = out["main.tf"] + assert "count = local.on ? 1 : 0" in main + assert "lifecycle {\n prevent_destroy = true\n }" in main + assert "depends_on = [aws_s3_bucket.a]" in main + assert "# C (Custom::Thing) was not converted" in main + assert 'variable "c_result"' in out["variables.tf"] + assert "value = var.c\n" in out["outputs.tf"] + messages = "\n".join(notes(template)) + for text in ( + "prevent_destroy", + "Terraform takes no snapshot", + "UpdateReplacePolicy Retain", + "has a CreationPolicy", + "cfn-init", + "custom resources run a Lambda function", + ): + assert text in messages + + +def test_unknown_depends_on_is_an_error(): + template = {"Resources": {"A": {"Type": "AWS::S3::Bucket", "DependsOn": "Nope"}}} + with pytest.raises(CfnError, match="DependsOn unknown resource 'Nope'"): + files(template) + + +def test_unsupported_types(): + template = { + "Resources": { + "S": {"Type": "AWS::CloudFormation::WaitConditionHandle"}, + "T": {"Type": "AWS::Made::Up"}, + } + } + result = convert_template(yaml.safe_dump(template)) + assert result["summary"] == {"resources": 2, "aws": 0, "awscc": 0, "unsupported": 2} + messages = "\n".join(result["notes"]) + assert "it exists inside CloudFormation only" in messages + assert "the aws mappings and the awscc provider both lack" in messages + assert [r["address"] for r in result["resources"]] == [None, None] + + +def test_leftover_properties_are_kept_as_comments_and_noted(): + template = { + "Resources": { + "B": { + "Type": "AWS::S3::Bucket", + "Properties": { + "Unknown": {"a": "b" * 200}, + "Gone": None, + "No": {"Ref": "AWS::NoValue"}, + }, + } + } + } + main = files(template)["main.tf"] + assert '# Unknown was not converted: {"a": "bbb' in main and "bbb...\n" in main + assert "Gone" not in main and "No was" not in main + assert any("'B.Unknown' was not converted" in n for n in notes(template)) + + +def test_generated_names_use_the_stack_name(): + template = {"Resources": {"T": {"Type": "AWS::DynamoDB::Table", "Properties": {}}}} + out = files(template, {"stack_name": "shop"}) + assert 'name = "${var.stack_name}-T"' in out["main.tf"] + assert any("had no TableName" in n for n in notes(template)) + + +# --- awscc ------------------------------------------------------------------------------ + + +def test_awscc_conversion_follows_the_schema_index(): + template = { + "Conditions": {"On": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Environment": {"Variables": {"MY_VAR": "1", "Other": {"Ref": "AWS::Region"}}}, + "Code": {"S3Bucket": "b", "S3Key": "k"}, + "VpcConfig": {"Fn::If": ["On", {"SubnetIds": ["s"]}, {"Ref": "AWS::NoValue"}]}, + "Tags": [{"Key": "k", "Value": "v"}], + "Skipped": None, + "TracingConfig": {"Mode": "Active", "Drop": {"Ref": "AWS::NoValue"}}, + }, + }, + "Role": { + "Type": "AWS::IAM::Role", + "Properties": {"AssumeRolePolicyDocument": {"Statement": []}}, + }, + "Param": { + "Type": "AWS::SSM::Parameter", + "Properties": { + "Type": "String", + "Value": "x", + "Tags": [{"Key": "a", "Value": "b"}], + }, + }, + "Env": { + "Type": "AWS::Cloud9::EnvironmentEC2", + "Properties": {"InstanceType": "t3.micro"}, + }, + }, + } + result = run(template, {"provider": "awscc"}) + main = result["files"][2]["content"] if len(result["files"]) > 2 else "" + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + assert 'resource "awscc_lambda_function" "fn"' in main + assert 'MY_VAR = "1"' in main and "Other = data.aws_region.current.region" in main + assert 's3_bucket = "b"' in main + assert 'vpc_config = local.on ? { subnet_ids = ["s"] } : null' in main + assert 'key = "k"' in main + assert "assume_role_policy_document = jsonencode({" in main + assert 'tags = {\n a = "b"\n }' in main + assert 'resource "awscc_cloud9_environment_ec2" "env"' in main + assert "drop" not in main + versions = result["files"][0]["content"] + assert "hashicorp/awscc" in versions and 'hashicorp/aws"' in versions + assert result["summary"]["awscc"] == 4 + assert any("the awscc provider was requested" in n for n in result["notes"]) + + +def test_awscc_only_template_has_no_aws_provider(): + template = {"Resources": {"Q": {"Type": "AWS::Batch::JobQueue", "Properties": {"Priority": 1}}}} + versions = files(template)["versions.tf"] + assert "hashicorp/awscc" in versions and 'hashicorp/aws"' not in versions + assert 'provider "awscc" {}' in versions + assert "AWS_REGION" in versions + + +# --- files, layouts, imports, outputs ------------------------------------------------- + + +def test_file_layouts(): + template = { + "Parameters": {"P": {"Type": "String"}}, + "Conditions": {"C": {"Fn::Equals": [{"Ref": "P"}, "x"]}}, + "Resources": BUCKET, + "Outputs": {"O": {"Value": {"Ref": "Bucket"}, "Description": "The bucket"}}, + } + split = files(template) + assert list(split) == ["versions.tf", "variables.tf", "locals.tf", "main.tf", "outputs.tf"] + assert 'description = "The bucket"' in split["outputs.tf"] + single = files(template, {"layout": "single"}) + assert list(single) == ["main.tf"] + text = single["main.tf"] + assert text.index("terraform {") < text.index('variable "p"') < text.index("locals {") + assert text.index("locals {") < text.index('resource "aws_s3_bucket"') < text.index("output") + + +def test_import_blocks(): + template = { + "Conditions": {"C": {"Fn::Equals": ["a", "a"]}}, + "Resources": { + "Named": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName": "my-bucket"}}, + "Unnamed": {"Type": "AWS::S3::Bucket", "Condition": "C"}, + "Cc": {"Type": "AWS::Batch::JobQueue", "Properties": {"Priority": 1}}, + }, + } + imports = files(template, {"include_imports": True})["imports.tf"] + assert "# Adopt the resources the stack created" in imports + assert 'to = aws_s3_bucket.named\n id = "my-bucket"' in imports + assert 'to = aws_s3_bucket.unnamed[0]\n id = "TODO: physical ID of Unnamed"' in imports + assert "to = awscc_batch_job_queue.cc" in imports + single = files(template, {"include_imports": True, "layout": "single"})["main.tf"] + assert single.rstrip().endswith("}") and "import {" in single + + +def test_outputs(): + template = { + "Conditions": {"C": {"Fn::Equals": ["a", "a"]}}, + "Resources": BUCKET, + "Outputs": { + "Name": { + "Value": {"Ref": "Bucket"}, + "Condition": "C", + "Export": {"Name": {"Fn::Sub": "${AWS::StackName}-bucket"}}, + }, + "Plain": {"Value": "x", "Export": {"Name": "plain-export"}}, + }, + } + out = files(template)["outputs.tf"] + assert "value = local.c ? aws_s3_bucket.bucket.id : null" in out + messages = "\n".join(notes(template)) + assert "exported as '${var.stack_name}-bucket'" in messages + assert "exported as 'plain-export'" in messages + + +def test_template_level_notes(): + template = { + "Transform": ["AWS::LanguageExtensions", "AWS::SecretsManager-2020-07-23", {"Name": "x"}], + "Rules": {"R": {}}, + "Extra": 1, + "Resources": BUCKET, + } + messages = "\n".join(notes(template)) + assert "Top-level section 'Extra'" in messages + assert "Transform 'AWS::SecretsManager-2020-07-23'" in messages + assert "Transform 'AWS::Include'" in messages + assert "Rules of the template were not converted" in messages + assert "LanguageExtensions" not in messages + + +def test_invalid_options(): + with pytest.raises(CfnError, match="Unknown provider"): + convert_template("Resources: {}", "google") + with pytest.raises(CfnError, match="Unknown layout"): + convert_template("Resources: {}", "aws", "tree") + + with pytest.raises(CfnError, match="Unknown provider"): + Converter({"Resources": {}}, provider="google") + converter = Converter({"Resources": BUCKET}) + with pytest.raises(CfnError, match="Unknown layout"): + converter.files("tree") + + +# --- edge paths ------------------------------------------------------------------------- + + +def test_awscc_renamed_types_missing_properties_and_local_code(): + + template = load_template( + yaml.safe_dump( + { + "Resources": { + "Oai": { + "Type": "AWS::CloudFront::CloudFrontOriginAccessIdentity", + "Properties": {"CloudFrontOriginAccessIdentityConfig": {"Comment": "c"}}, + }, + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": {"Handler": "a.b", "Role": "arn:r"}, + }, + "Layer": {"Type": "AWS::Lambda::LayerVersion", "Properties": {}}, + "Topic": { + "Type": "AWS::SNS::Topic", + "Properties": {"DeliveryPolicy": {"x": 1}}, + }, + "Logs": { + "Type": "AWS::Logs::LogGroup", + "Properties": {"DeletionProtectionEnabled": True, "RetentionInDays": 1}, + }, + "Glue": { + "Type": "AWS::Glue::Catalog", + "Properties": { + "Name": "c", + "FederatedCatalog": {"ConnectionType": "x", "Identifier": "i"}, + }, + }, + } + } + ) + ) + converter = Converter( + template, + provider="awscc", + hints={"Fn": {"code_path": "src"}, "Layer": {"code_path": "layer"}}, + ) + result = converter.run("single") + main = result["files"][0]["content"] + messages = "\n".join(result["notes"]) + assert 'resource "awscc_cloudfront_cloudfront_origin_access_identity" "oai"' in main + assert "s3_bucket = var.fn_code_bucket" in main and "s3_key = var.fn_code_key" in main + assert "content = {" in main and "var.layer_code_bucket" in main + assert "the awscc provider takes Lambda code from S3 only" in messages + assert "# DeliveryPolicy was not converted" in main + assert "# DeletionProtectionEnabled was not converted" in main + assert ( + "'Glue.FederatedCatalog.ConnectionType' is missing from awscc_glue_catalog in this " + "provider version" in messages + ) + + +def fill_a(props: Props) -> None: + """Copy property A to attribute a.""" + props.attr("a", "A") + + +def test_body_items_must_be_hcl_nodes(): + with pytest.raises(TypeError, match="Unexpected body item"): + hcl.BodyWriter(0).write([object()]) + + +def test_blocks_from_computed_values(): + + ctx = Context({"Conditions": {"C": {}}, "Resources": {}}) + ctx.conditions["C"] = "c" + props = Props( + ctx, + { + "Text": "not a mapping", + "Short": {"Fn::If": ["C", {}]}, + "Inverted": {"Fn::If": ["C", {"Ref": "AWS::NoValue"}, {"A": 1}]}, + "Both": {"Fn::If": ["C", {"A": 1}, {"A": 2}]}, + }, + "R", + "R (X)", + ) + for name in ("Text", "Short", "Inverted", "Both"): + props.block(name.lower(), name, fill_a) + rendered = hcl.render_block(Block("resource", ["x", "y"], props.items)) + assert "# Text was not converted" in rendered + assert "# Short was not converted" in rendered + assert 'dynamic "inverted" {\n for_each = !local.c ? [1] : []' in rendered + assert "# Both was not converted" in rendered + assert sum("computed by a function" in n for n in ctx.notes) == 3 + + +def test_json_values_and_template_parts(): + + ctx = Context({"Resources": {}}) + assert ctx.json("not json") == "not json" + assert ctx.json('{"a": 1}') == Call("jsonencode", {"a": 1}) + assert ctx.json({"Fn::Sub": "x"}) == "x" + assert ctx.json([1]) == Call("jsonencode", [1]) + assert ( + expression({"Fn::Join": ["", [False, {"Fn::Base64": "x"}]]}) + == '"false${base64encode("x")}"' + ) + template = {"Parameters": {"N": {"Type": "String"}}} + assert "range(var.n)" in expression({"Fn::Cidr": ["10.0.0.0/16", {"Ref": "N"}, 8]}, template) + + +def test_render_comment_inside_an_object_and_mapping_tags(): + assert hcl.render({"a": 1, "note": Comment("why")}) == "{\n a = 1\n # why\n}" + template = load_template( + "Resources:\n B:\n Type: X\n Properties:\n V: !Transform {Name: M}\n" + ) + assert template["Resources"]["B"]["Properties"]["V"] == {"Fn::Transform": {"Name": "M"}} + + +def test_remaining_small_paths(): + assert ( + expression({"Fn::Join": ["-", [1, {"Ref": "Bucket"}]]}) == '"1-${aws_s3_bucket.bucket.id}"' + ) + assert awscc_type("AWS::Redshift::QEV2IdcApplication") == "awscc_redshift_qev2_idc_application" + template = { + "Resources": { + "Q": { + "Type": "AWS::Batch::JobQueue", + "Properties": {"Priority": 1, "State": {"Ref": "AWS::NoValue"}}, + }, + "B": { + "Type": "AWS::S3::Bucket", + "Properties": { + "CorsConfiguration": { + "CorsRules": [ + {"AllowedMethods": ["GET"], "AllowedOrigins": ["*"], "MaxAge": "soon"} + ] + } + }, + }, + } + } + main = files(template)["main.tf"] + assert "state" not in main.split('resource "awscc_batch_job_queue"')[1].split("}")[0] + assert 'max_age_seconds = "soon"' in main + + +def test_lists_drop_no_value_items(): + template = {"Conditions": {"C": {"Fn::Equals": ["a", "b"]}}} + assert expression(["a", {"Ref": "AWS::NoValue"}], template) == '["a"]' + assert expression(["a", {"Fn::If": ["C", "b", {"Ref": "AWS::NoValue"}]}], template) == ( + '[for item in ["a", local.c ? "b" : null] : item if item != null]' + ) + assert expression([{"Fn::If": ["C", {"Ref": "AWS::NoValue"}, "b"]}], template) == ( + '[for item in [local.c ? null : "b"] : item if item != null]' + ) + assert expression([{"Fn::If": ["C", "a", "b"]}], template) == '[local.c ? "a" : "b"]' + + +def test_optional_items_and_literal_guard(): + + ctx = Context({"Resources": {}}) + ctx.conditions["C"] = "c" + no = {"Ref": "AWS::NoValue"} + assert ctx.optional_item({"Fn::If": ["C", "x", no]}) == ("local.c", "x") + assert ctx.optional_item({"Fn::If": ["C", no, "x"]}) == ("!local.c", "x") + assert ctx.optional_item({"Fn::If": ["C", "x", "y"]}) == (None, {"Fn::If": ["C", "x", "y"]}) + assert ctx.optional_item({"Fn::If": "bad"}) == (None, {"Fn::If": "bad"}) + assert ctx.optional_item("x") == (None, "x") + + props = Props(ctx, {"L": [1], "M": {"Ref": "X"}, "S": "text"}, "R", "R (T)") + assert props.literal("L", list) == [1] + assert props.literal("M", dict) is None and props.literal("S", list) is None + assert props.literal("Gone", list) is None + assert props.literal("V", dict, value={"a": 1}) == {"a": 1} + assert sum("is computed by a function" in n for n in ctx.notes) == 2 + + info = ResourceInfo("R", "AWS::X::Y", "aws_x", "r") + plain = Builder(ctx, info, {"Type": "AWS::X::Y"}) + assert plain.count_items() == [] + assert hcl.inline(plain.count_items("local.c")[0].value) == "local.c ? 1 : 0" + counted = Builder(ctx, info, {"Type": "AWS::X::Y", "Condition": "C"}) + assert hcl.inline(counted.count_items("!local.c")[0].value) == "local.c && (!local.c) ? 1 : 0" + counted.add_resource("aws_y", "_extra", [], when="local.c") + assert "count = local.c && (local.c) ? 1 : 0" in hcl.render_block(counted.extra[0]) + + +def test_awscc_if_with_wrong_arguments_is_an_error(): + template = { + "Conditions": {"C": {"Fn::Equals": ["a", "b"]}}, + "Resources": { + "Q": { + "Type": "AWS::Batch::JobQueue", + "Properties": {"Priority": {"Fn::If": ["C", 1]}}, + } + }, + } + with pytest.raises(CfnError, match="Fn::If"): + run(template, {"provider": "awscc"}) diff --git a/services/converter-api/tests/test_cfn_data.py b/services/converter-api/tests/test_cfn_data.py new file mode 100644 index 0000000..6de2c19 --- /dev/null +++ b/services/converter-api/tests/test_cfn_data.py @@ -0,0 +1,305 @@ +"""RDS, KMS, Secrets Manager and SSM mappings.""" + +from __future__ import annotations + +import json +import re + +from converters.cfn.pipeline import convert_template + + +def convert( + resources: dict, + parameters: dict | None = None, + conditions: dict | None = None, + outputs: dict | None = None, +) -> tuple[str, list[str]]: + template: dict = {"Resources": resources} + for section, value in ( + ("Parameters", parameters), + ("Conditions", conditions), + ("Outputs", outputs), + ): + if value is not None: + template[section] = value + result = convert_template(json.dumps(template), stack_name="demo") + files = {f["path"]: f["content"] for f in result["files"]} + return files["main.tf"] + files.get("outputs.tf", ""), result["notes"] + + +def squash(text: str) -> str: + """HCL without the alignment spaces before '='.""" + return re.sub(r" +=", " =", text) + + +def _db(policy: str | None = None, props: dict | None = None) -> dict: + resource: dict = { + "Type": "AWS::RDS::DBInstance", + "Properties": {"Engine": "postgres", "DBInstanceClass": "db.t4g.micro"} | (props or {}), + } + if policy: + resource["DeletionPolicy"] = policy + return resource + + +def test_db_instance_final_snapshot_follows_the_deletion_policy(): + main, notes = convert( + { + "Default": _db(), + "Named": _db("Retain", {"DBInstanceIdentifier": "named-db"}), + "Gone": _db("Delete"), + "Snap": _db("Snapshot"), + }, + outputs={ + "Id": {"Value": {"Ref": "Default"}}, + "Arn": {"Value": {"Fn::GetAtt": ["Default", "DBInstanceArn"]}}, + "Zone": {"Value": {"Fn::GetAtt": ["Default", "Endpoint.HostedZoneId"]}}, + "Res": {"Value": {"Fn::GetAtt": ["Default", "DbiResourceId"]}}, + }, + ) + assert 'final_snapshot_identifier = "default-final-snapshot"' in main + assert 'final_snapshot_identifier = "named-db-final-snapshot"' in main + assert 'final_snapshot_identifier = "snap-final-snapshot"' in main + assert main.count("skip_final_snapshot = true") == 1 + assert any("Default: CloudFormation snapshots this database" in n for n in notes) + assert not any(n.startswith("Snap: CloudFormation snapshots") for n in notes) + assert not any("Snap has DeletionPolicy Snapshot" in n for n in notes) + for attribute in ("identifier", "arn", "hosted_zone_id", "resource_id"): + assert f"aws_db_instance.default.{attribute}" in main + + +def test_db_instance_password_note(): + main, notes = convert( + {"Db": _db("Delete", {"MasterUserPassword": "secret", "MasterUsername": "u"})} + ) + assert 'password = "secret"' in main + assert any("Db: the master password ends up in the Terraform state" in n for n in notes) + + +def test_db_instance_master_secret_without_key(): + main, _ = convert({"Db": _db("Delete", {"MasterUserSecret": {}})}) + assert "master_user_secret_kms_key_id" not in main + + +def test_parameter_group_values(): + main, notes = convert( + { + "Params": { + "Type": "AWS::RDS::DBParameterGroup", + "Properties": { + "Family": "postgres16", + "Description": "d", + "Parameters": {"a": 1, "b": {"Ref": "Value"}}, + }, + }, + "Computed": { + "Type": "AWS::RDS::DBParameterGroup", + "Properties": { + "Family": "postgres16", + "Description": "d", + "Parameters": {"Fn::If": ["On", {}, {}]}, + }, + }, + }, + parameters={"Value": {"Type": "String"}}, + conditions={"On": {"Fn::Equals": [1, 1]}}, + ) + assert 'value = "1"' in main + assert "value = var.value" in main + assert "apply_method" not in main + assert any("Computed.Parameters' was not converted" in n for n in notes) + + +def test_cluster_attributes_and_password(): + main, notes = convert( + { + "Cluster": { + "Type": "AWS::RDS::DBCluster", + "DeletionPolicy": "Delete", + "Properties": { + "Engine": "aurora-mysql", + "MasterUsername": "u", + "MasterUserPassword": "p", + "MasterUserSecret": {"KmsKeyId": "k"}, + }, + } + }, + outputs={ + "Id": {"Value": {"Ref": "Cluster"}}, + "Read": {"Value": {"Fn::GetAtt": ["Cluster", "ReadEndpoint.Address"]}}, + "Secret": {"Value": {"Fn::GetAtt": ["Cluster", "MasterUserSecret.SecretArn"]}}, + }, + ) + assert 'master_password = "p"' in main + assert 'master_user_secret_kms_key_id = "k"' in main + assert "skip_final_snapshot = true" in main + assert "aws_rds_cluster.cluster.cluster_identifier" in main + assert "aws_rds_cluster.cluster.reader_endpoint" in main + assert "aws_rds_cluster.cluster.master_user_secret[0].secret_arn" in main + assert any("write-only master_password_wo" in n for n in notes) + + +def test_kms_references(): + main, _ = convert( + { + "Key": {"Type": "AWS::KMS::Key", "Properties": {"Description": "k"}}, + "Alias": { + "Type": "AWS::KMS::Alias", + "Properties": { + "AliasName": "alias/k", + "TargetKeyId": {"Fn::GetAtt": ["Key", "KeyId"]}, + }, + }, + }, + outputs={"Alias": {"Value": {"Ref": "Alias"}}, "Key": {"Value": {"Ref": "Key"}}}, + ) + assert "target_key_id = aws_kms_key.key.key_id" in main + assert "aws_kms_alias.alias.name" in main + + +def test_secret_with_generated_value_is_reported(): + main, notes = convert( + { + "Secret": { + "Type": "AWS::SecretsManager::Secret", + "Properties": {"GenerateSecretString": {"PasswordLength": 32}}, + } + }, + outputs={"Arn": {"Value": {"Ref": "Secret"}}}, + ) + assert "GenerateSecretString was not converted" in main + assert any("random_password and secret_string_wo or convert this secret" in n for n in notes) + assert "aws_secretsmanager_secret_version" not in main + assert "aws_secretsmanager_secret.secret.arn" in main + + +def test_ssm_parameter_references(): + main, _ = convert( + { + "P": { + "Type": "AWS::SSM::Parameter", + "Properties": {"Name": "/p", "Type": "String", "Value": "v"}, + } + }, + outputs={ + "Name": {"Value": {"Ref": "P"}}, + "Value": {"Value": {"Fn::GetAtt": ["P", "Value"]}, "Description": "v"}, + }, + ) + assert "aws_ssm_parameter.p.name" in main + assert "aws_ssm_parameter.p.value" in main + + +def test_rds_names_are_lowercased_as_cloudformation_stores_them(): + main, _ = convert( + { + "Db": _db(props={"DBInstanceIdentifier": "MyDatabase"}), + "Cluster": { + "Type": "AWS::RDS::DBCluster", + "Properties": { + "Engine": "aurora-postgresql", + "DBClusterIdentifier": {"Fn::Sub": "${AWS::StackName}-Cluster"}, + }, + }, + "Subnets": { + "Type": "AWS::RDS::DBSubnetGroup", + "Properties": { + "DBSubnetGroupName": {"Ref": "GroupName"}, + "DBSubnetGroupDescription": "d", + "SubnetIds": ["subnet-1"], + }, + }, + "Params": { + "Type": "AWS::RDS::DBParameterGroup", + "Properties": { + "DBParameterGroupName": "MyParams", + "Family": "postgres16", + "Description": "d", + }, + }, + "Ref": _db("Delete", {"DBInstanceIdentifier": {"Ref": "Params"}}), + }, + parameters={"GroupName": {"Type": "String"}}, + ) + main = squash(main) + assert 'identifier = "mydatabase"' in main + assert 'final_snapshot_identifier = "mydatabase-final-snapshot"' in main + assert 'cluster_identifier = lower("${var.stack_name}-Cluster")' in main + assert "name = lower(var.group_name)" in main + assert 'name = "myparams"' in main + # A reference to a resource of the template is already lowercase. + assert "identifier = aws_db_parameter_group.params.name" in main + + +def test_db_instance_applies_changes_immediately_like_cloudformation(): + main, notes = convert( + {"Now": _db("Delete"), "Later": _db("Delete", {"ApplyImmediately": False})}, + ) + main = squash(main) + assert main.count("apply_immediately = true") == 1 + assert main.count("apply_immediately = false") == 1 + assert not any("ApplyImmediately" in n for n in notes) + + +def test_cluster_member_instance_is_a_cluster_instance(): + main, notes = convert( + { + "Cluster": { + "Type": "AWS::RDS::DBCluster", + "DeletionPolicy": "Delete", + "Properties": {"Engine": "aurora-postgresql"}, + }, + "Member": _db( + props={ + "DBClusterIdentifier": {"Ref": "Cluster"}, + "Engine": "aurora-postgresql", + "DBInstanceIdentifier": "Member-1", + "DBInstanceClass": "db.serverless", + "DBParameterGroupName": "params", + "PromotionTier": 1, + "PubliclyAccessible": False, + "MonitoringInterval": "60", + "Tags": [{"Key": "a", "Value": "b"}], + } + ), + }, + outputs={ + "Address": {"Value": {"Fn::GetAtt": ["Member", "Endpoint.Address"]}}, + "Port": {"Value": {"Fn::GetAtt": ["Member", "Endpoint.Port"]}}, + "Res": {"Value": {"Fn::GetAtt": ["Member", "DbiResourceId"]}}, + "Id": {"Value": {"Ref": "Member"}}, + }, + ) + main = squash(main) + assert 'resource "aws_rds_cluster_instance" "member"' in main + assert "cluster_identifier = aws_rds_cluster.cluster.cluster_identifier" in main + assert 'identifier = "member-1"' in main + assert 'db_parameter_group_name = "params"' in main + assert "promotion_tier = 1" in main + assert "apply_immediately = true" in main + member = main.split('resource "aws_rds_cluster_instance" "member"')[1] + assert "final_snapshot" not in member + assert not any(n.startswith("Member: CloudFormation snapshots") for n in notes) + assert not any("not converted" in n for n in notes) + for attribute in ("endpoint", "port", "dbi_resource_id", "identifier"): + assert f"aws_rds_cluster_instance.member.{attribute}" in main + + +def test_parameter_group_applies_parameters_the_default_way(): + main, notes = convert( + { + "Params": { + "Type": "AWS::RDS::DBParameterGroup", + "Properties": { + "Family": "postgres16", + "Description": "d", + "Parameters": {"log_connections": True, "rds.force_ssl": False}, + }, + }, + } + ) + main = squash(main) + assert 'value = "true"' in main + assert 'value = "false"' in main + assert "apply_method" not in main + assert any('needs apply_method = "pending-reboot"' in n for n in notes) diff --git a/services/converter-api/tests/test_cfn_iam.py b/services/converter-api/tests/test_cfn_iam.py new file mode 100644 index 0000000..e202dd7 --- /dev/null +++ b/services/converter-api/tests/test_cfn_iam.py @@ -0,0 +1,362 @@ +"""IAM mappings: roles, policies, instance profiles, users and groups.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +import pytest + +from converters.cfn.pipeline import convert_template + +FIXTURES = Path(__file__).parent / "fixtures" / "cfn" +TRUST = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"Service": "ec2.amazonaws.com"}, + "Action": "sts:AssumeRole", + } + ], +} +DOC = { + "Version": "2012-10-17", + "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}], +} + + +def convert( + resources: dict, + parameters: dict | None = None, + conditions: dict | None = None, + outputs: dict | None = None, +) -> tuple[str, list[str], dict]: + template: dict = {"Resources": resources} + for section, value in ( + ("Parameters", parameters), + ("Conditions", conditions), + ("Outputs", outputs), + ): + if value is not None: + template[section] = value + result = convert_template(json.dumps(template), stack_name="demo") + files = {f["path"]: f["content"] for f in result["files"]} + return files["main.tf"], result["notes"], files + + +@pytest.mark.parametrize("name", ["iam", "messaging", "observability", "data"]) +def test_fixtures_convert_every_property(name): + result = convert_template((FIXTURES / f"{name}.yaml").read_text(), stack_name="demo") + assert not [n for n in result["notes"] if "not converted" in n] + assert result["summary"]["awscc"] == 0 and result["summary"]["unsupported"] == 0 + + +def test_role_with_inline_and_managed_policies(): + main, notes, files = convert( + { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": TRUST, + "MaxSessionDuration": "3600", + "PermissionsBoundary": "arn:aws:iam::aws:policy/PowerUserAccess", + "Policies": [ + {"PolicyName": "a", "PolicyDocument": DOC}, + {"PolicyName": "a", "PolicyDocument": DOC}, + {"PolicyName": {"Fn::Sub": "${AWS::StackName}-p"}, "PolicyDocument": DOC}, + {"PolicyName": {"Ref": "AWS::StackName"}, "PolicyDocument": DOC}, + {"PolicyDocument": DOC}, + ], + "ManagedPolicyArns": [ + "arn:aws:iam::aws:policy/ReadOnlyAccess", + "arn:aws:iam::aws:policy/ReadOnlyAccess", + {"Fn::Sub": ["arn:${P}:iam::aws:policy/X", {"P": "aws"}]}, + {"Fn::ImportValue": "shared-policy"}, + ], + }, + } + }, + outputs={"Id": {"Value": {"Fn::GetAtt": ["Role", "RoleId"]}}}, + ) + assert 'resource "aws_iam_role" "role"' in main + assert "max_session_duration = 3600" in main + assert 'permissions_boundary = "arn:aws:iam::aws:policy/PowerUserAccess"' in main + assert 'resource "aws_iam_role_policy" "role_a"' in main + assert 'resource "aws_iam_role_policy" "role_a_2"' in main + assert 'resource "aws_iam_role_policy" "role_aws_stack_name_p"' in main + assert 'resource "aws_iam_role_policy" "role_policy_4"' in main + assert 'resource "aws_iam_role_policy" "role_policy_5"' in main + assert "role = aws_iam_role.role.name" in main + assert 'resource "aws_iam_role_policy_attachment" "role_read_only_access"' in main + assert 'resource "aws_iam_role_policy_attachment" "role_read_only_access_2"' in main + assert 'resource "aws_iam_role_policy_attachment" "role_x"' in main + assert 'resource "aws_iam_role_policy_attachment" "role_policy_4"' in main + assert "inline_policy" not in main and "managed_policy_arns" not in main + assert "aws_iam_role.role.unique_id" in files["outputs.tf"] + assert not [n for n in notes if "not converted" in n] + + +def test_role_policies_computed_by_functions_are_reported(): + main, notes, _ = convert( + { + "Role": { + "Type": "AWS::IAM::Role", + "Condition": "On", + "Properties": { + "AssumeRolePolicyDocument": TRUST, + "Policies": [{"Fn::If": ["On", {"PolicyName": "x"}, {"PolicyName": "y"}]}], + "ManagedPolicyArns": {"Fn::If": ["On", ["arn:a"], []]}, + }, + } + }, + conditions={"On": {"Fn::Equals": ["a", "a"]}}, + ) + assert "Policies[0] was not converted" in main + assert "ManagedPolicyArns was not converted" in main + assert any("inline policy 1 is computed by a function" in n for n in notes) + assert any("ManagedPolicyArns is computed by a function" in n for n in notes) + assert "count = local.on ? 1 : 0" in main + + +def test_role_policies_as_a_single_mapping(): + main, _, _ = convert( + { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": TRUST, + "Policies": {"PolicyName": "only", "PolicyDocument": DOC}, + }, + } + } + ) + assert 'resource "aws_iam_role_policy" "role_only"' in main + + +def test_policy_attached_to_roles_users_and_groups(): + main, notes, _ = convert( + { + "Role": {"Type": "AWS::IAM::Role", "Properties": {"AssumeRolePolicyDocument": TRUST}}, + "Policy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "p", + "PolicyDocument": DOC, + "Roles": [{"Ref": "Role"}, "literal-role"], + "Users": ["alice"], + "Groups": [{"Fn::Sub": "${AWS::StackName}-admins"}, {"Fn::ImportValue": "g"}], + }, + }, + } + ) + assert 'resource "aws_iam_role_policy" "policy"' in main + assert "role = aws_iam_role.role.name" in main + assert 'resource "aws_iam_role_policy" "policy_literal_role"' in main + assert 'resource "aws_iam_user_policy" "policy_alice"' in main + assert 'user = "alice"' in main + assert 'resource "aws_iam_group_policy" "policy_aws_stack_name_admins"' in main + assert 'resource "aws_iam_group_policy" "policy_group_5"' in main + assert not [n for n in notes if "not converted" in n] + + +def test_policy_type_follows_the_first_principal(): + main, _, _ = convert( + { + "Policy": { + "Type": "AWS::IAM::Policy", + "Properties": {"PolicyDocument": DOC, "Users": ["bob"]}, + } + }, + outputs={"P": {"Value": {"Ref": "Policy"}}}, + ) + assert 'resource "aws_iam_user_policy" "policy"' in main + assert "name =" not in main + + +def test_policy_without_readable_principals_gets_a_variable(): + main, notes, files = convert( + { + "Policy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "p", + "PolicyDocument": DOC, + "Roles": {"Fn::Split": [",", "a,b"]}, + }, + } + } + ) + assert 'resource "aws_iam_role_policy" "policy"' in main + assert "role = var.policy_role" in main + assert "Roles was not converted" in main + assert 'variable "policy_role"' in files["variables.tf"] + assert any("lists no role, user or group" in n for n in notes) + + +def test_managed_policy_and_attachments(): + main, _, files = convert( + { + "Managed": { + "Type": "AWS::IAM::ManagedPolicy", + "Properties": { + "PolicyDocument": DOC, + "Roles": [{"Ref": "AWS::StackName"}], + "Users": [{"Fn::Join": ["", ["u"]]}], + "Groups": ["ops"], + }, + } + }, + outputs={ + "Arn": {"Value": {"Ref": "Managed"}}, + "Id": {"Value": {"Fn::GetAtt": ["Managed", "PolicyId"]}}, + }, + ) + assert 'resource "aws_iam_policy" "managed"' in main + assert 'resource "aws_iam_role_policy_attachment" "managed_aws_stack_name"' in main + assert 'resource "aws_iam_user_policy_attachment" "managed_u"' in main + assert 'resource "aws_iam_group_policy_attachment" "managed_ops"' in main + assert "policy_arn = aws_iam_policy.managed.arn" in main + assert "aws_iam_policy.managed.policy_id" in files["outputs.tf"] + + +def test_instance_profile_takes_its_one_role(): + main, notes, files = convert( + { + "Profile": {"Type": "AWS::IAM::InstanceProfile", "Properties": {"Roles": ["r"]}}, + "Two": {"Type": "AWS::IAM::InstanceProfile", "Properties": {"Roles": ["a", "b"]}}, + }, + outputs={"Arn": {"Value": {"Fn::GetAtt": ["Profile", "Arn"]}}}, + ) + assert 'role = "r"' in main + assert any("Two.Roles' was not converted" in n for n in notes) + assert "aws_iam_instance_profile.profile.arn" in files["outputs.tf"] + + +def test_user_and_group(): + main, notes, _ = convert( + { + "User": { + "Type": "AWS::IAM::User", + "Properties": { + "Groups": ["ops"], + "PermissionsBoundary": "arn:aws:iam::aws:policy/PowerUserAccess", + "Policies": [{"PolicyName": "p", "PolicyDocument": DOC}], + "ManagedPolicyArns": ["arn:aws:iam::aws:policy/ReadOnlyAccess"], + "LoginProfile": {"Password": "x"}, + }, + }, + "Group": { + "Type": "AWS::IAM::Group", + "Properties": { + "Policies": [{"PolicyName": "p", "PolicyDocument": DOC}], + "ManagedPolicyArns": ["arn:aws:iam::aws:policy/ReadOnlyAccess"], + }, + }, + } + ) + assert 'name = "${var.stack_name}-User"' in main + assert 'resource "aws_iam_user_group_membership" "user_groups"' in main + assert 'resource "aws_iam_user_policy" "user_p"' in main + assert 'resource "aws_iam_user_policy_attachment" "user_read_only_access"' in main + assert 'name = "${var.stack_name}-Group"' in main + assert 'resource "aws_iam_group_policy" "group_p"' in main + assert 'resource "aws_iam_group_policy_attachment" "group_read_only_access"' in main + assert any("User.LoginProfile' was not converted" in n for n in notes) + assert any("Group had no GroupName" in n for n in notes) + + +def squash(text: str) -> str: + """HCL without the alignment spaces before '='.""" + return re.sub(r" +=", " =", text) + + +ON = {"On": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}} +ENV = {"Env": {"Type": "String"}} + + +def _if(value: object) -> dict: + return {"Fn::If": ["On", value, {"Ref": "AWS::NoValue"}]} + + +def _unless(value: object) -> dict: + return {"Fn::If": ["On", {"Ref": "AWS::NoValue"}, value]} + + +def test_optional_managed_policies_and_inline_policies_are_counted(): + main, notes, _ = convert( + { + "Role": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": TRUST, + "ManagedPolicyArns": [ + "arn:aws:iam::aws:policy/ReadOnlyAccess", + _if("arn:aws:iam::aws:policy/AdministratorAccess"), + {"Ref": "AWS::NoValue"}, + ], + "Policies": [ + _unless({"PolicyName": "dev", "PolicyDocument": DOC}), + {"Ref": "AWS::NoValue"}, + ], + }, + } + }, + parameters=ENV, + conditions=ON, + ) + main = squash(main) + admin = main.split('"aws_iam_role_policy_attachment" "role_administrator_access"')[1] + assert admin.startswith(" {\n count = local.on ? 1 : 0") + assert 'policy_arn = "arn:aws:iam::aws:policy/AdministratorAccess"' in admin + assert "null" not in main + dev = main.split('"aws_iam_role_policy" "role_dev"')[1] + assert dev.startswith(" {\n count = !local.on ? 1 : 0") + assert main.count("aws_iam_role_policy_attachment") == 2 + assert not any("not converted" in n or "computed by a function" in n for n in notes) + + +def test_policy_with_optional_principals(): + main, _, files = convert( + { + "Role": {"Type": "AWS::IAM::Role", "Properties": {"AssumeRolePolicyDocument": TRUST}}, + "User": {"Type": "AWS::IAM::User"}, + "Policy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "p", + "PolicyDocument": DOC, + "Roles": [_if({"Ref": "Role"}), {"Ref": "AWS::NoValue"}], + "Users": [{"Ref": "User"}], + }, + }, + "OnlyOptional": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": "q", + "PolicyDocument": DOC, + "Roles": [_if({"Ref": "Role"})], + }, + }, + "Managed": { + "Type": "AWS::IAM::ManagedPolicy", + "Properties": {"PolicyDocument": DOC, "Groups": [_if("admins")]}, + }, + }, + parameters=ENV, + conditions=ON, + outputs={"Ref": {"Value": {"Ref": "OnlyOptional"}}}, + ) + main = squash(main) + # The principal that is always there gets the main resource. + policy = main.split('resource "aws_iam_user_policy" "policy" {')[1].split("\n}")[0] + assert "count" not in policy and "user = aws_iam_user.user.name" in policy + role = main.split('resource "aws_iam_role_policy" "policy_role" {')[1].split("\n}")[0] + assert "count = local.on ? 1 : 0" in role and "role = aws_iam_role.role.name" in role + only = main.split('resource "aws_iam_role_policy" "only_optional" {')[1].split("\n}")[0] + assert "count = local.on ? 1 : 0" in only + assert "aws_iam_role_policy.only_optional[0].id" in files["outputs.tf"] + group = main.split('"aws_iam_group_policy_attachment" "managed_admins" {')[1] + assert group.startswith("\n count = local.on ? 1 : 0") and 'group = "admins"' in group + assert "null" not in main diff --git a/services/converter-api/tests/test_cfn_messaging.py b/services/converter-api/tests/test_cfn_messaging.py new file mode 100644 index 0000000..ed49aad --- /dev/null +++ b/services/converter-api/tests/test_cfn_messaging.py @@ -0,0 +1,600 @@ +"""SQS, SNS, EventBridge, Kinesis and Step Functions mappings.""" + +from __future__ import annotations + +import json +import re + +from converters.cfn.pipeline import convert_template +from converters.cfn.resources.messaging import sub_json + +DOC = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}]} +ROLE = "arn:aws:iam::123456789012:role/r" + + +def convert( + resources: dict, + parameters: dict | None = None, + conditions: dict | None = None, + outputs: dict | None = None, +) -> tuple[str, list[str]]: + template: dict = {"Resources": resources} + for section, value in ( + ("Parameters", parameters), + ("Conditions", conditions), + ("Outputs", outputs), + ): + if value is not None: + template[section] = value + result = convert_template(json.dumps(template), stack_name="demo") + files = {f["path"]: f["content"] for f in result["files"]} + return files["main.tf"] + files.get("outputs.tf", ""), result["notes"] + + +def test_queue_reference_attributes(): + main, notes = convert( + {"Q": {"Type": "AWS::SQS::Queue", "Properties": {"VisibilityTimeout": "30"}}}, + outputs={ + "Url": {"Value": {"Ref": "Q"}}, + "Arn": {"Value": {"Fn::GetAtt": ["Q", "Arn"]}}, + "Name": {"Value": {"Fn::GetAtt": ["Q", "QueueName"]}}, + "Url2": {"Value": {"Fn::GetAtt": ["Q", "QueueUrl"]}}, + }, + ) + assert "visibility_timeout_seconds = 30" in main + for text in ("aws_sqs_queue.q.url", "aws_sqs_queue.q.arn", "aws_sqs_queue.q.name"): + assert text in main + assert notes == [] + + +def test_queue_policy_for_several_queues_and_a_computed_list(): + main, notes = convert( + { + "A": {"Type": "AWS::SQS::Queue"}, + "Policy": { + "Type": "AWS::SQS::QueuePolicy", + "Properties": { + "Queues": [{"Ref": "A"}, "https://sqs/b", {"Ref": "A"}], + "PolicyDocument": DOC, + }, + }, + "Computed": { + "Type": "AWS::SQS::QueuePolicy", + "Properties": {"Queues": {"Fn::Split": [",", "a,b"]}, "PolicyDocument": DOC}, + }, + } + ) + assert 'resource "aws_sqs_queue_policy" "policy"' in main + assert "queue_url = aws_sqs_queue.a.url" in main + assert 'resource "aws_sqs_queue_policy" "policy_target_2"' in main + assert 'resource "aws_sqs_queue_policy" "policy_a"' in main + assert "Queues was not converted" in main + assert any("Computed.Queues' was not converted" in n for n in notes) + + +def test_topic_subscriptions(): + main, notes = convert( + { + "One": { + "Type": "AWS::SNS::Topic", + "Properties": {"Subscription": [{"Protocol": "email", "Endpoint": "a@b.c"}]}, + }, + "Computed": { + "Type": "AWS::SNS::Topic", + "Condition": "On", + "Properties": {"Subscription": {"Fn::If": ["On", [], []]}}, + }, + "Plain": {"Type": "AWS::SNS::Topic"}, + "Policy": { + "Type": "AWS::SNS::TopicPolicy", + "Properties": {"Topics": [{"Ref": "One"}], "PolicyDocument": DOC}, + }, + }, + conditions={"On": {"Fn::Equals": [1, 1]}}, + outputs={"Name": {"Value": {"Fn::GetAtt": ["One", "TopicName"]}}}, + ) + assert 'resource "aws_sns_topic_subscription" "one_subscription"' in main + assert "topic_arn = aws_sns_topic.one.arn" in main + assert "Subscription was not converted" in main + assert any("Computed: Subscription is computed" in n for n in notes) + assert 'resource "aws_sns_topic" "plain" {}' in main + assert "arn = aws_sns_topic.one.arn" in main + assert "aws_sns_topic.one.name" in main + + +def test_subscription_region_and_policies(): + main, _ = convert( + { + "Sub": { + "Type": "AWS::SNS::Subscription", + "Properties": { + "TopicArn": "arn:aws:sns:us-east-1:1:t", + "Protocol": "lambda", + "Endpoint": "arn:aws:lambda:us-east-1:1:function:f", + "Region": "us-east-1", + "SubscriptionRoleArn": ROLE, + "DeliveryPolicy": {"healthyRetryPolicy": {"numRetries": 3}}, + "ReplayPolicy": {"PointType": "Timestamp"}, + }, + } + } + ) + assert 'region = "us-east-1"' in main + assert "delivery_policy = jsonencode({" in main + assert "replay_policy = jsonencode({" in main + + +def test_rule_targets_of_every_kind(): + main, notes = convert( + { + "Rule": { + "Type": "AWS::Events::Rule", + "Properties": { + "ScheduleExpression": "rate(5 minutes)", + "EventBusName": {"Ref": "AWS::NoValue"}, + "Targets": [ + { + "Id": {"Fn::Sub": "${AWS::StackName}-t"}, + "Arn": "arn:aws:execute-api:us-east-1:1:api/stage/GET/", + "HttpParameters": { + "HeaderParameters": {"X-Key": "v"}, + "PathParameterValues": ["a"], + "QueryStringParameters": {"q": "1"}, + }, + }, + { + "Id": "batch", + "Arn": "arn:aws:batch:us-east-1:1:job-queue/q", + "RoleArn": ROLE, + "BatchParameters": { + "JobDefinition": "def", + "JobName": "job", + "ArrayProperties": {"Size": 2}, + "RetryStrategy": {"Attempts": 3}, + }, + }, + { + "Id": "ecs", + "Arn": "arn:aws:ecs:us-east-1:1:cluster/c", + "RoleArn": ROLE, + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:1:task-definition/t:1", + "TaskCount": "1", + "LaunchType": "FARGATE", + "PlatformVersion": "LATEST", + "Group": "g", + "EnableECSManagedTags": True, + "EnableExecuteCommand": False, + "PropagateTags": "TASK_DEFINITION", + "NetworkConfiguration": { + "AwsVpcConfiguration": { + "Subnets": ["subnet-1"], + "SecurityGroups": ["sg-1"], + "AssignPublicIp": "ENABLED", + } + }, + }, + }, + { + "Id": "ecs2", + "Arn": "arn:aws:ecs:us-east-1:1:cluster/c", + "EcsParameters": { + "TaskDefinitionArn": "t", + "NetworkConfiguration": {"AwsVpcConfiguration": {"Subnets": ["s"]}}, + }, + }, + { + "Id": "ecs3", + "Arn": "arn:aws:ecs:us-east-1:1:cluster/c", + "EcsParameters": {"TaskDefinitionArn": "t"}, + }, + { + "Id": "batch2", + "Arn": "arn:aws:batch:us-east-1:1:job-queue/q", + "BatchParameters": {"JobDefinition": "d", "JobName": "j"}, + }, + ], + }, + }, + "Bare": { + "Type": "AWS::Events::Rule", + "Properties": {"ScheduleExpression": "rate(1 hour)"}, + }, + "Computed": { + "Type": "AWS::Events::Rule", + "Properties": {"Targets": {"Fn::If": ["On", [], []]}}, + }, + }, + conditions={"On": {"Fn::Equals": [1, 1]}}, + ) + assert 'resource "aws_cloudwatch_event_target" "rule_target_1"' in main + assert "event_bus_name" not in main.split('"rule_target_1"')[1].split("}")[0] + assert "http_target {" in main and "header_parameters = {" in main + assert "array_size = 2" in main and "job_attempts = 3" in main + assert "assign_public_ip = true" in main + assert 'subnets = ["s"]' in main + assert 'resource "aws_cloudwatch_event_target" "rule_ecs3"' in main + assert any("Computed: Targets is computed" in n for n in notes) + assert not [n for n in notes if "property" in n] + + +def test_event_bus_without_policy_and_plain_stream(): + main, notes = convert( + { + "Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": "b"}}, + "Stream": {"Type": "AWS::Kinesis::Stream", "Properties": {"ShardCount": 1}}, + } + ) + assert "aws_cloudwatch_event_bus_policy" not in main + assert 'name = "${var.stack_name}-Stream"' in main + assert any("Stream had no Name" in n for n in notes) + + +def _machine(props: dict) -> dict: + return { + "M": {"Type": "AWS::StepFunctions::StateMachine", "Properties": {"RoleArn": ROLE} | props} + } + + +def test_definition_substitutions_on_an_object(): + main, notes = convert( + _machine( + { + "Definition": { + "StartAt": "A", + "States": { + "A": { + "Type": "Task", + "Resource": "${Fn}", + "Comment": "calls ${Fn} with ${Other}", + "Next": "${Missing}", + "Branches": [{"Note": "plain"}], + } + }, + }, + "DefinitionSubstitutions": {"Fn": {"Fn::GetAtt": ["Q", "Arn"]}}, + } + ) + | {"Q": {"Type": "AWS::SQS::Queue"}}, + outputs={"Name": {"Value": {"Fn::GetAtt": ["M", "Name"]}}}, + ) + assert "Resource = aws_sqs_queue.q.arn" in main + assert '"calls ${aws_sqs_queue.q.arn} with $${Other}"' in main + assert 'Next = "${Missing}"' not in main and '"$${Missing}"' in main + assert "aws_sfn_state_machine.m.name" in main + assert notes == [] or not [n for n in notes if "not converted" in n] + + +def test_definition_string_forms(): + main, notes = convert( + _machine({"DefinitionString": '{"StartAt": "A", "States": {}}'}) + | { + "Bad": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "DefinitionString": "not json ${X}", + "DefinitionSubstitutions": {"X": "1"}, + }, + }, + "SubList": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "DefinitionString": { + "Fn::Sub": ['{"StartAt": "${S}", "States": {}}', {"S": "First"}] + }, + }, + }, + "SubText": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "DefinitionString": {"Fn::Sub": "not ${AWS::Region}"}, + }, + }, + "Joined": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "DefinitionString": {"Fn::Join": ["", ['{"StartAt":', '"A"}']]}, + }, + }, + } + ) + assert 'StartAt = "A"' in main + assert 'definition = "not json ${X}"' not in main and 'definition = "not json $${X}"' in main + assert any("Bad: DefinitionSubstitutions could not be applied" in n for n in notes) + assert 'StartAt = "First"' in main + assert 'definition = "not ${data.aws_region.current.region}"' in main + assert 'definition = "{\\"StartAt\\":\\"A\\"}"' in main + + +def test_sub_json_keeps_plain_placeholders(): + assert sub_json({"Fn::Sub": '{"a": "${AWS::Region}", "b": ["x"]}'}) == { + "a": {"Fn::Sub": "${AWS::Region}"}, + "b": ["x"], + } + assert sub_json({"Fn::Sub": [1, {}]}) is None + + +def test_bus_policy_rule_on_a_bus_and_stream_encryption(): + main, _ = convert( + { + "Bus": { + "Type": "AWS::Events::EventBus", + "Properties": {"Name": "b", "Policy": DOC}, + }, + "Rule": { + "Type": "AWS::Events::Rule", + "Properties": {"EventBusName": "b", "Targets": [{"Id": "t", "Arn": "arn:x"}]}, + }, + "Stream": { + "Type": "AWS::Kinesis::Stream", + "Properties": { + "Name": "s", + "StreamEncryption": {"EncryptionType": "KMS", "KeyId": "alias/k"}, + }, + }, + } + ) + assert 'resource "aws_cloudwatch_event_bus_policy" "bus_policy"' in main + assert 'event_bus_name = "b"' in main + assert 'encryption_type = "KMS"' in main and 'kms_key_id = "alias/k"' in main + + +def test_log_destinations(): + main, _ = convert( + _machine( + { + "Definition": {"StartAt": "A", "States": {}}, + "LoggingConfiguration": { + "Level": "ALL", + "Destinations": [ + {"CloudWatchLogsLogGroup": {"LogGroupArn": "arn:aws:logs:r:1:log-group:g"}} + ], + }, + "EncryptionConfiguration": {"Type": "AWS_OWNED_KEY"}, + } + ) + | { + "Kept": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "Definition": {}, + "LoggingConfiguration": { + "Destinations": [ + { + "CloudWatchLogsLogGroup": { + "LogGroupArn": "arn:aws:logs:r:1:log-group:g:*" + } + } + ] + }, + }, + }, + "Param": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "Definition": {}, + "LoggingConfiguration": { + "Destinations": [ + {"CloudWatchLogsLogGroup": {"LogGroupArn": {"Ref": "LogArn"}}} + ] + }, + }, + }, + "Empty": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "Definition": {}, + "LoggingConfiguration": {"Level": "OFF", "Destinations": [{}]}, + }, + }, + "None": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "Definition": {}, + "LoggingConfiguration": {"Level": "OFF"}, + }, + }, + }, + parameters={"LogArn": {"Type": "String"}}, + ) + assert 'log_destination = "arn:aws:logs:r:1:log-group:g:*"' in main + assert main.count(':log-group:g:*"') == 2 + assert 'log_destination = "${var.log_arn}:*"' in main + assert 'type = "AWS_OWNED_KEY"' in main + + +def squash(text: str) -> str: + """HCL without the alignment spaces before '='.""" + return re.sub(r" +=", " =", text) + + +ON = {"On": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}} +ENV = {"Env": {"Type": "String"}} +NO = {"Ref": "AWS::NoValue"} + + +def _if(value: object) -> dict: + return {"Fn::If": ["On", value, NO]} + + +def _block(main: str, header: str) -> str: + return main.split(header + " {")[1].split("\n}")[0] + + +def test_policies_for_optional_queues_and_topics_are_counted(): + main, notes = convert( + { + "A": {"Type": "AWS::SQS::Queue"}, + "B": {"Type": "AWS::SQS::Queue"}, + "T": {"Type": "AWS::SNS::Topic"}, + "QP": { + "Type": "AWS::SQS::QueuePolicy", + "Properties": { + "PolicyDocument": DOC, + "Queues": [_if({"Ref": "B"}), {"Ref": "A"}, NO], + }, + }, + "TP": { + "Type": "AWS::SNS::TopicPolicy", + "Properties": {"PolicyDocument": DOC, "Topics": [_if({"Ref": "T"})]}, + }, + }, + parameters=ENV, + conditions=ON, + outputs={"Id": {"Value": {"Ref": "TP"}}}, + ) + main = squash(main) + main_policy = _block(main, 'resource "aws_sqs_queue_policy" "qp"') + assert "count" not in main_policy and "queue_url = aws_sqs_queue.a.url" in main_policy + copy = _block(main, 'resource "aws_sqs_queue_policy" "qp_b"') + assert "count = local.on ? 1 : 0" in copy and "queue_url = aws_sqs_queue.b.url" in copy + topic = _block(main, 'resource "aws_sns_topic_policy" "tp"') + assert "count = local.on ? 1 : 0" in topic and "arn = aws_sns_topic.t.arn" in topic + assert "aws_sns_topic_policy.tp[0].id" in main + assert "null" not in main + assert notes == [] + + +def test_optional_subscriptions_and_rule_targets_are_counted(): + main, notes = convert( + { + "Q": {"Type": "AWS::SQS::Queue"}, + "Topic": { + "Type": "AWS::SNS::Topic", + "Properties": { + "Subscription": [ + _if({"Protocol": "email", "Endpoint": "ops@example.com"}), + NO, + {"Fn::If": ["On", {"Protocol": "sqs"}, {"Protocol": "email"}]}, + ] + }, + }, + "Rule": { + "Type": "AWS::Events::Rule", + "Properties": { + "ScheduleExpression": "rate(5 minutes)", + "Targets": [ + _if({"Id": "q", "Arn": {"Fn::GetAtt": ["Q", "Arn"]}}), + NO, + {"Ref": "Targets"}, + ], + }, + }, + }, + parameters=ENV | {"Targets": {"Type": "String"}}, + conditions=ON, + ) + main = squash(main) + subscription = _block(main, 'resource "aws_sns_topic_subscription" "topic_subscription_1"') + assert "count = local.on ? 1 : 0" in subscription + assert ( + 'protocol = "email"' in subscription + and "topic_arn = aws_sns_topic.topic.arn" in subscription + ) + target = _block(main, 'resource "aws_cloudwatch_event_target" "rule_q"') + assert "count = local.on ? 1 : 0" in target and "arn = aws_sqs_queue.q.arn" in target + assert main.count('resource "aws_sns_topic_subscription"') == 1 + assert main.count('resource "aws_cloudwatch_event_target"') == 1 + assert "Subscription[2] was not converted" in main + assert "Targets[2] was not converted" in main + assert any("'Topic.Subscription[2]' is computed by a function" in n for n in notes) + assert any("'Rule.Targets[2]' is computed by a function" in n for n in notes) + + +def _ecs_rule(network: object) -> dict: + return { + "Type": "AWS::Events::Rule", + "Properties": { + "ScheduleExpression": "rate(1 hour)", + "Targets": [ + { + "Id": "t", + "Arn": "arn:aws:ecs:us-east-1:123456789012:cluster/c", + "RoleArn": ROLE, + "EcsParameters": { + "TaskDefinitionArn": "arn:task-definition/t:1", + "NetworkConfiguration": network, + "ArrayProperties": {"Ref": "Size"}, + }, + } + ], + }, + } + + +def test_ecs_target_network_configuration_from_functions(): + main, notes = convert( + { + "Public": _ecs_rule( + { + "AwsVpcConfiguration": { + "Subnets": ["subnet-1"], + "AssignPublicIp": {"Fn::If": ["On", "ENABLED", "DISABLED"]}, + } + } + ), + "Computed": _ecs_rule({"Ref": "Network"}), + "Inner": _ecs_rule({"AwsVpcConfiguration": {"Ref": "Network"}}), + }, + parameters=ENV | {"Network": {"Type": "String"}, "Size": {"Type": "String"}}, + conditions=ON, + ) + main = squash(main) + assert 'assign_public_ip = (local.on ? "ENABLED" : "DISABLED") == "ENABLED"' in main + assert "NetworkConfiguration was not converted" in main + assert "AwsVpcConfiguration was not converted" in main + assert "ArrayProperties was not converted" in main + assert any("Computed.Targets[0].EcsParameters.NetworkConfiguration" in n for n in notes) + assert any("Inner.Targets[0].EcsParameters.NetworkConfiguration.AwsVpc" in n for n in notes) + + +def test_definition_substitutions_stay_text(): + main, _ = convert( + { + "Machine": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": ROLE, + "DefinitionString": json.dumps( + { + "StartAt": "A", + "States": { + "A": { + "Type": "Pass", + "Result": { + "n": "${N}", + "f": "${F}", + "b": "${B}", + "p": "${P}", + "s": "${S}", + "mixed": "n=${N}", + }, + "End": True, + } + }, + } + ), + "DefinitionSubstitutions": { + "N": 5, + "F": 1.5, + "B": True, + "P": {"Ref": "Retries"}, + "S": {"Ref": "Name"}, + }, + }, + } + }, + parameters={"Retries": {"Type": "Number"}, "Name": {"Type": "String"}}, + ) + main = squash(main) + for line in ('n = "5"', 'f = "1.5"', 'b = "true"', "p = tostring(var.retries)", "s = var.name"): + assert line in main + assert 'mixed = "n=5"' in main diff --git a/services/converter-api/tests/test_cfn_network.py b/services/converter-api/tests/test_cfn_network.py new file mode 100644 index 0000000..dfbe67a --- /dev/null +++ b/services/converter-api/tests/test_cfn_network.py @@ -0,0 +1,1307 @@ +"""Network mappings: VPC, security groups, load balancers, Route 53, ACM, CloudFront.""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +from converters.cfn.pipeline import convert_template +from converters.cfn.resources.network import _refers_to + +FIXTURE = Path(__file__).parent / "fixtures" / "cfn" / "network.yaml" + + +def convert( + resources: dict, + parameters: dict | None = None, + conditions: dict | None = None, + outputs: dict | None = None, +) -> tuple[str, list[str]]: + template: dict = {"Resources": resources} + for section, value in ( + ("Parameters", parameters), + ("Conditions", conditions), + ("Outputs", outputs), + ): + if value is not None: + template[section] = value + result = convert_template( + yaml.safe_dump(template, sort_keys=False), layout="single", stack_name="demo" + ) + # Whitespace-insensitive: alignment depends on the neighbouring attributes. + return " ".join(result["files"][0]["content"].split()), result["notes"] + + +def test_fixture_converts_without_notes(): + result = convert_template(FIXTURE.read_text(), stack_name="demo") + assert result["notes"] == [] + assert result["summary"]["aws"] == result["summary"]["resources"] + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + assert 'resource "aws_acm_certificate_validation" "certificate"' in main + assert "cloudfront_default_certificate = true" in main + + +# --- VPC basics --------------------------------------------------------------------------- + + +def test_vpc_subnet_and_ipv6_lists(): + hcl, notes = convert( + { + "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}}, + "Subnet": { + "Type": "AWS::EC2::Subnet", + "Properties": { + "VpcId": {"Ref": "Vpc"}, + "CidrBlock": "10.0.0.0/24", + "PrivateDnsNameOptionsOnLaunch": { + "HostnameType": "resource-name", + "EnableResourceNameDnsARecord": "true", + "EnableResourceNameDnsAAAARecord": False, + "Other": 1, + }, + }, + }, + }, + outputs={ + "VpcV6": {"Value": {"Fn::Select": [0, {"Fn::GetAtt": ["Vpc", "Ipv6CidrBlocks"]}]}}, + "SubnetV6": { + "Value": {"Fn::Select": [0, {"Fn::GetAtt": ["Subnet", "Ipv6CidrBlocks"]}]} + }, + }, + ) + assert "element([aws_vpc.vpc.ipv6_cidr_block], 0)" in hcl + assert "element([aws_subnet.subnet.ipv6_cidr_block], 0)" in hcl + assert 'private_dns_hostname_type_on_launch = "resource-name"' in hcl + assert "enable_resource_name_dns_a_record_on_launch = true" in hcl + assert "enable_resource_name_dns_aaaa_record_on_launch = false" in hcl + assert any("PrivateDnsNameOptionsOnLaunch.Other" in n for n in notes) + + +def test_gateways_routes_and_eip_association(): + hcl, notes = convert( + { + "Egress": { + "Type": "AWS::EC2::EgressOnlyInternetGateway", + "Properties": {"VpcId": "vpc-1"}, + }, + "Vpn": { + "Type": "AWS::EC2::VPCGatewayAttachment", + "Properties": {"VpcId": "vpc-1", "VpnGatewayId": "vgw-1"}, + }, + "ToInstance": { + "Type": "AWS::EC2::Route", + "Properties": {"RouteTableId": "rtb-1", "InstanceId": "i-1"}, + }, + "Assoc": { + "Type": "AWS::EC2::EIPAssociation", + "Properties": {"AllocationId": "eipalloc-1", "InstanceId": "i-1"}, + }, + } + ) + assert 'resource "aws_egress_only_internet_gateway" "egress"' in hcl + assert 'resource "aws_vpn_gateway_attachment" "vpn"' in hcl + assert 'vpn_gateway_id = "vgw-1"' in hcl + assert 'resource "aws_eip_association" "assoc"' in hcl + assert any("routes to an instance" in n for n in notes) + assert any("ToInstance.InstanceId" in n for n in notes) + + +# --- security groups ---------------------------------------------------------------------- + + +def test_inline_rules_ports_protocols_and_default_egress(): + hcl, notes = convert( + { + "Sg": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "x", + "SecurityGroupIngress": [ + {"IpProtocol": "icmp", "CidrIp": "10.0.0.0/8"}, + {"IpProtocol": "tcp", "FromPort": 22, "SourceSecurityGroupId": "sg-1"}, + {"IpProtocol": "udp", "SourcePrefixListId": "pl-1"}, + {"IpProtocol": {"Ref": "Proto"}, "FromPort": 1, "ToPort": 2}, + ], + }, + } + }, + parameters={"Proto": {"Type": "String"}}, + ) + assert 'from_port = -1 to_port = -1 protocol = "icmp"' in hcl + assert 'from_port = 22 to_port = 22 protocol = "tcp"' in hcl + assert 'security_groups = ["sg-1"]' in hcl + assert "to_port = 65535" in hcl and 'prefix_list_ids = ["pl-1"]' in hcl + assert "protocol = var.proto" in hcl + assert "CloudFormation adds this allow-all egress rule" in hcl + assert notes == [] + + +def test_inline_egress_and_conditional_rule(): + hcl, _ = convert( + { + "Sg": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "x", + "SecurityGroupIngress": [ + { + "Fn::If": [ + "Open", + { + "IpProtocol": "tcp", + "FromPort": 80, + "ToPort": 80, + "CidrIp": "0.0.0.0/0", + }, + {"Ref": "AWS::NoValue"}, + ] + } + ], + "SecurityGroupEgress": [ + {"IpProtocol": "-1", "DestinationSecurityGroupId": "sg-2"}, + { + "IpProtocol": 6, + "FromPort": 443, + "ToPort": 443, + "DestinationPrefixListId": "pl-2", + }, + ], + }, + } + }, + conditions={"Open": {"Fn::Equals": ["a", "a"]}}, + ) + assert 'dynamic "ingress"' in hcl and "for_each = local.open ? [1] : []" in hcl + assert 'security_groups = ["sg-2"]' in hcl + assert 'protocol = "6"' in hcl and 'prefix_list_ids = ["pl-2"]' in hcl + assert "allow-all egress" not in hcl + + +def test_group_with_standalone_rules_gets_rule_resources(): + hcl, notes = convert( + { + "Sg": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "x", + "SecurityGroupIngress": [ + {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "CidrIpv6": "::/0"} + ], + }, + }, + "Other": { + "Type": "AWS::EC2::SecurityGroup", + "Properties": { + "GroupDescription": "y", + "SecurityGroupIngress": {"Fn::If": ["C", [], []]}, + "SecurityGroupEgress": [{"IpProtocol": "-1", "CidrIp": "0.0.0.0/0"}], + }, + }, + "In": { + "Type": "AWS::EC2::SecurityGroupIngress", + "Properties": { + "GroupId": {"Fn::GetAtt": ["Sg", "GroupId"]}, + "IpProtocol": {"Ref": "Proto"}, + "SourceSecurityGroupId": {"Ref": "Other"}, + }, + }, + "Out": { + "Type": "AWS::EC2::SecurityGroupEgress", + "Properties": { + "GroupId": {"Fn::GetAtt": "Other.GroupId"}, + "IpProtocol": "tcp", + "FromPort": 5432, + "ToPort": 5432, + "DestinationPrefixListId": "pl-1", + "GroupName": "default", + }, + }, + "In2": { + "Type": "AWS::EC2::SecurityGroupIngress", + "Properties": { + "GroupId": {"Ref": "Other"}, + "IpProtocol": "-1", + "CidrIp": "10.0.0.0/8", + }, + }, + "Out2": { + "Type": "AWS::EC2::SecurityGroupEgress", + "Properties": {"GroupId": {"Fn::GetAtt": "Other.GroupId"}, "IpProtocol": "-1"}, + }, + }, + parameters={"Proto": {"Type": "String"}}, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + ) + assert 'resource "aws_vpc_security_group_ingress_rule" "sg_ingress_1"' in hcl + assert 'resource "aws_vpc_security_group_egress_rule" "other_egress_1"' in hcl + assert 'resource "aws_vpc_security_group_egress_rule" "sg_egress_1"' in hcl + assert 'cidr_ipv6 = "::/0"' in hcl + assert "ingress {" not in hcl + assert any( + "Other: the ingress rules are computed by a function, so they were not turned into" in n + for n in notes + ) + assert "ip_protocol = var.proto" in hcl + assert 'prefix_list_id = "pl-1"' in hcl + assert any("Out.GroupName" in n for n in notes) + + +# --- network ACLs and flow logs ----------------------------------------------------------- + + +def test_network_acl_entry_and_flow_log(): + hcl, notes = convert( + { + "Entry": { + "Type": "AWS::EC2::NetworkAclEntry", + "Properties": { + "NetworkAclId": "acl-1", + "RuleNumber": "200", + "Protocol": {"Ref": "Proto"}, + "Egress": "true", + "RuleAction": "deny", + "Ipv6CidrBlock": "::/0", + "Icmp": {"Type": -1, "Code": -1}, + }, + }, + "Logs": { + "Type": "AWS::EC2::FlowLog", + "Properties": { + "ResourceType": "VPC", + "ResourceId": "vpc-1", + "TrafficType": "ALL", + "LogGroupName": "flow-logs", + "DeliverLogsPermissionArn": "arn:role", + "MaxAggregationInterval": 60, + "DestinationOptions": {"FileFormat": "parquet", "PerHourPartition": True}, + }, + }, + }, + parameters={"Proto": {"Type": "String"}}, + ) + assert "protocol = var.proto" in hcl and "icmp_type = -1" in hcl + assert "egress = true" in hcl + assert 'vpc_id = "vpc-1"' in hcl + assert ( + "arn:${data.aws_partition.current.partition}:logs:${data.aws_region.current.region}:" + "${data.aws_caller_identity.current.account_id}:log-group:flow-logs" in hcl + ) + assert 'file_format = "parquet"' in hcl + assert notes == [] + + +# --- load balancers ----------------------------------------------------------------------- + + +def test_load_balancer_attributes_and_logs(): + hcl, notes = convert( + { + "Lb": { + "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", + "Properties": { + "Scheme": {"Ref": "Scheme"}, + "Type": "network", + "SubnetMappings": [{"SubnetId": "subnet-1", "AllocationId": "eipalloc-1"}], + "LoadBalancerAttributes": [ + {"Key": "access_logs.s3.enabled", "Value": "true"}, + {"Key": "connection_logs.s3.bucket", "Value": "logs"}, + {"Key": "load_balancing.cross_zone.enabled", "Value": "true"}, + {"Key": "routing.http.desync_mitigation_mode", "Value": "strictest"}, + {"Key": "made.up", "Value": "1"}, + ], + }, + }, + "Internal": { + "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", + "Properties": { + "Scheme": "internal", + "LoadBalancerAttributes": {"Fn::If": ["C", [], []]}, + }, + }, + }, + parameters={"Scheme": {"Type": "String"}}, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + ) + assert 'internal = var.scheme == "internal"' in hcl + assert "internal = true" in hcl + assert 'access_logs { bucket = "" enabled = true }' in hcl + assert 'connection_logs { bucket = "logs" }' in hcl + assert "enable_cross_zone_load_balancing = true" in hcl + assert 'desync_mitigation_mode = "strictest"' in hcl + assert "subnet_mapping {" in hcl and 'allocation_id = "eipalloc-1"' in hcl + assert any("LoadBalancerAttributes 'made.up'" in n for n in notes) + assert any("Internal.LoadBalancerAttributes' is computed" in n for n in notes) + + +def test_target_group_attributes_health_and_targets(): + hcl, notes = convert( + { + "Tg": { + "Type": "AWS::ElasticLoadBalancingV2::TargetGroup", + "Properties": { + "Port": 50051, + "Protocol": "HTTP", + "ProtocolVersion": "GRPC", + "Matcher": {"GrpcCode": "0-99"}, + "TargetGroupAttributes": [ + {"Key": "stickiness.enabled", "Value": "true"}, + {"Key": "stickiness.type", "Value": "app_cookie"}, + {"Key": "stickiness.app_cookie.cookie_name", "Value": "sid"}, + {"Key": "slow_start.duration_seconds", "Value": "30"}, + {"Key": "unknown.key", "Value": "x"}, + ], + "Targets": [{"Id": "i-1", "Port": 80}, {"Id": "i-2"}], + }, + }, + "Computed": { + "Type": "AWS::ElasticLoadBalancingV2::TargetGroup", + "Properties": {"Targets": {"Fn::If": ["C", [], []]}, "Matcher": {}}, + }, + }, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + ) + assert 'matcher = "0-99"' in hcl + assert 'type = "app_cookie"' in hcl and 'cookie_name = "sid"' in hcl + assert "slow_start = 30" in hcl + assert 'resource "aws_lb_target_group_attachment" "tg_target_2"' in hcl + assert "target_group_arn = aws_lb_target_group.tg.arn" in hcl + assert any("'unknown.key'" in n for n in notes) + assert any("Computed: Targets is computed" in n for n in notes) + assert "health_check" not in hcl.split('"computed"')[1] + + +def test_listener_actions_and_certificates(): + hcl, notes = convert( + { + "Listener": { + "Type": "AWS::ElasticLoadBalancingV2::Listener", + "Properties": { + "LoadBalancerArn": "arn:lb", + "Port": "443", + "Protocol": "TLS", + "AlpnPolicy": ["HTTP2Preferred"], + "Certificates": [{"CertificateArn": "arn:c1"}, {"CertificateArn": "arn:c2"}], + "DefaultActions": [ + { + "Type": "authenticate-cognito", + "Order": 1, + "AuthenticateCognitoConfig": { + "UserPoolArn": "arn:pool", + "UserPoolClientId": "client", + "UserPoolDomain": "auth", + "SessionTimeout": "3600", + }, + }, + { + "Type": "authenticate-oidc", + "Order": 2, + "AuthenticateOidcConfig": { + "AuthorizationEndpoint": "https://a", + "ClientId": "c", + "ClientSecret": "s", + "Issuer": "https://i", + "TokenEndpoint": "https://t", + "UserInfoEndpoint": "https://u", + "UseExistingClientSecret": False, + }, + }, + { + "Type": "forward", + "Order": 3, + "ForwardConfig": { + "TargetGroups": [ + {"TargetGroupArn": "arn:tg1", "Weight": "80"}, + {"TargetGroupArn": "arn:tg2"}, + ], + "TargetGroupStickinessConfig": { + "Enabled": True, + "DurationSeconds": 60, + }, + }, + }, + {"Type": "forward", "TargetGroupArn": "arn:tg1", "ForwardConfig": {}}, + ], + }, + }, + "Computed": { + "Type": "AWS::ElasticLoadBalancingV2::Listener", + "Properties": { + "LoadBalancerArn": "arn:lb", + "Certificates": {"Fn::If": ["C", [], []]}, + "AlpnPolicy": "None", + }, + }, + "Extra": { + "Type": "AWS::ElasticLoadBalancingV2::ListenerCertificate", + "Properties": { + "ListenerArn": {"Ref": "Listener"}, + "Certificates": [{"CertificateArn": "arn:c3"}, {"CertificateArn": "arn:c4"}], + }, + }, + }, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + ) + assert 'alpn_policy = "HTTP2Preferred"' in hcl + assert 'certificate_arn = "arn:c1"' in hcl + assert 'resource "aws_lb_listener_certificate" "listener_certificate_2"' in hcl + assert 'certificate_arn = "arn:c2"' in hcl + assert 'user_pool_domain = "auth"' in hcl and "session_timeout = 3600" in hcl + assert 'user_info_endpoint = "https://u"' in hcl + assert "weight = 80" in hcl and "duration = 60" in hcl + assert hcl.count('target_group { arn = "arn:tg') == 2 + assert 'alpn_policy = "None"' in hcl + assert any("Computed: Certificates is computed" in n for n in notes) + assert 'resource "aws_lb_listener_certificate" "extra"' in hcl + assert "listener_arn = aws_lb_listener.listener.arn" in hcl + assert 'resource "aws_lb_listener_certificate" "extra_certificate_2"' in hcl + assert not any("ForwardConfig" in n for n in notes) + + +def test_listener_rule_conditions(): + hcl, notes = convert( + { + "Rule": { + "Type": "AWS::ElasticLoadBalancingV2::ListenerRule", + "Properties": { + "ListenerArn": "arn:l", + "Priority": 5, + "Actions": [{"Type": "forward", "TargetGroupArn": "arn:tg"}], + "Conditions": [ + {"Field": "host-header", "Values": ["a.example.com"]}, + { + "Field": "http-header", + "HttpHeaderConfig": { + "HttpHeaderName": "X-Env", + "Values": ["blue"], + }, + }, + { + "Field": "query-string", + "QueryStringConfig": { + "Values": [{"Key": "v", "Value": "2"}, {"Value": "beta"}], + }, + }, + {"Field": "source-ip", "SourceIpConfig": {"Values": "10.0.0.0/8"}}, + {"Field": "path-pattern", "PathPatternConfig": {"RegexValues": ["^/a"]}}, + {"Field": "made-up"}, + ], + }, + } + } + ) + assert 'host_header { values = ["a.example.com"]' in hcl + assert 'http_header_name = "X-Env"' in hcl + assert 'key = "v"' in hcl and 'value = "beta"' in hcl + assert 'values = ["10.0.0.0/8"]' in hcl + assert 'regex_values = ["^/a"]' in hcl + assert any("rule condition 'made-up'" in n for n in notes) + + +# --- Route 53 ----------------------------------------------------------------------------- + + +def test_hosted_zone_and_records(): + hcl, notes = convert( + { + "Zone": { + "Type": "AWS::Route53::HostedZone", + "Properties": { + "Name": "Example.com", + "VPCs": [{"VPCId": "vpc-1", "VPCRegion": "eu-west-1"}], + "HostedZoneTags": [{"Key": "team", "Value": "web"}], + }, + }, + "Local": { + "Type": "AWS::Route53::RecordSet", + "Properties": { + "HostedZoneName": "example.com.", + "Name": "a.example.com", + "Type": "A", + "TTL": 60, + "ResourceRecords": ["1.2.3.4"], + "SetIdentifier": "eu", + "Weight": "10", + "Comment": "ignored", + }, + }, + "Remote": { + "Type": "AWS::Route53::RecordSet", + "Condition": "C", + "Properties": { + "HostedZoneName": "other.com.", + "Name": "b.other.com", + "Type": "CNAME", + "TTL": "60", + "ResourceRecords": ["x.other.com"], + "SetIdentifier": "x", + "Region": "eu-west-1", + "Failover": "PRIMARY", + "GeoLocation": {"ContinentCode": "EU"}, + "HealthCheckId": "hc-1", + }, + }, + "NoZone": { + "Type": "AWS::Route53::RecordSet", + "Properties": {"Name": "d", "Type": "A", "ResourceRecords": ["1.1.1.1"]}, + }, + "Computed": { + "Type": "AWS::Route53::RecordSet", + "Properties": {"HostedZoneName": {"Ref": "ZoneName"}, "Name": "c", "Type": "A"}, + }, + }, + parameters={"ZoneName": {"Type": "String"}}, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + ) + assert 'vpc { vpc_id = "vpc-1"' in hcl + assert "team = " in hcl + assert "zone_id = aws_route53_zone.zone.id" in hcl + assert "weighted_routing_policy { weight = 10" in hcl + assert 'data "aws_route53_zone" "remote_zone"' in hcl + assert "zone_id = data.aws_route53_zone.remote_zone[0].zone_id" in hcl + assert 'latency_routing_policy { region = "eu-west-1"' in hcl + assert 'failover_routing_policy { type = "PRIMARY"' in hcl + assert 'continent = "EU"' in hcl + assert "name = var.zone_name" in hcl + assert "data.aws_route53_zone.computed_zone.zone_id" in hcl + assert notes == [] + + +def test_record_set_group(): + hcl, notes = convert( + { + "Group": { + "Type": "AWS::Route53::RecordSetGroup", + "Properties": { + "HostedZoneName": "example.com.", + "Comment": "x", + "RecordSets": [ + { + "Name": "a.example.com", + "Type": "A", + "TTL": 60, + "ResourceRecords": ["1.1.1.1"], + }, + { + "Name": "b.example.com", + "Type": "A", + "AliasTarget": { + "DNSName": "d.cloudfront.net", + "HostedZoneId": "Z2FDTNDATAQYW2", + }, + }, + ], + }, + }, + "Empty": {"Type": "AWS::Route53::RecordSetGroup", "Properties": {"RecordSets": []}}, + } + ) + assert hcl.count('data "aws_route53_zone" "group_zone"') == 1 + assert 'resource "aws_route53_record" "group_2"' in hcl + assert "evaluate_target_health = false" in hcl + assert any("Empty: RecordSets is empty" in n for n in notes) + + +# --- ACM ---------------------------------------------------------------------------------- + + +def test_certificate_validation_variants(): + hcl, notes = convert( + { + "Email": { + "Type": "AWS::CertificateManager::Certificate", + "Properties": { + "DomainName": "a.com", + "ValidationMethod": "EMAIL", + "CertificateTransparencyLoggingPreference": "DISABLED", + "DomainValidationOptions": [ + {"DomainName": "a.com", "ValidationDomain": "a.com"}, + "not-a-mapping", + ], + }, + }, + "NoZone": { + "Type": "AWS::CertificateManager::Certificate", + "Properties": {"DomainName": "b.com", "ValidationMethod": "DNS"}, + }, + "TwoZones": { + "Type": "AWS::CertificateManager::Certificate", + "Condition": "C", + "Properties": { + "DomainName": "c.com", + "SubjectAlternativeNames": ["d.com"], + "ValidationMethod": "DNS", + "DomainValidationOptions": [ + {"DomainName": "c.com", "HostedZoneId": "Z1"}, + {"DomainName": "d.com", "HostedZoneId": "Z2"}, + ], + }, + }, + }, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + outputs={"Arn": {"Value": {"Ref": "TwoZones"}, "Condition": "C"}}, + ) + assert 'certificate_transparency_logging_preference = "DISABLED"' in hcl + assert 'validation_option { domain_name = "a.com"' in hcl + assert any("NoZone is validated by DNS without a hosted zone" in n for n in notes) + assert "flatten(aws_acm_certificate.two_zones[*].domain_validation_options)" in hcl + assert 'lookup({ "c.com" = "Z1", "d.com" = "Z2" }, each.key, "Z1")' in hcl + assert "certificate_arn = aws_acm_certificate.two_zones[0].arn" in hcl + assert "aws_acm_certificate_validation.two_zones[0].certificate_arn" in hcl + + +# --- CloudFront --------------------------------------------------------------------------- + + +def test_distribution_full_config(): + hcl, notes = convert( + { + "Oai": { + "Type": "AWS::CloudFront::CloudFrontOriginAccessIdentity", + "Properties": {"CloudFrontOriginAccessIdentityConfig": {"Comment": "site"}}, + }, + "Cdn": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "Tags": [{"Key": "app", "Value": "site"}], + "DistributionConfig": { + "Enabled": True, + "Aliases": ["www.example.com"], + "Logging": {"Bucket": "logs.s3.amazonaws.com", "IncludeCookies": False}, + "Origins": [ + { + "Id": "s3", + "DomainName": "b.s3.amazonaws.com", + "OriginCustomHeaders": [{"HeaderName": "X-A", "HeaderValue": "1"}], + "S3OriginConfig": { + "OriginAccessIdentity": { + "Fn::Sub": "origin-access-identity/cloudfront/${Oai}" + }, + "OriginReadTimeout": 30, + }, + "OriginShield": { + "Enabled": True, + "OriginShieldRegion": "us-east-1", + }, + }, + { + "Id": "web", + "DomainName": "example.org", + "CustomOriginConfig": {"OriginProtocolPolicy": "match-viewer"}, + }, + { + "Id": "vpc", + "DomainName": "internal", + "VpcOriginConfig": {"VpcOriginId": "vo-1"}, + }, + ], + "OriginGroups": { + "Quantity": 1, + "Items": [ + { + "Id": "group", + "FailoverCriteria": {"StatusCodes": {"Items": [500, "502"]}}, + "Members": {"Items": [{"OriginId": "s3"}, {"OriginId": "web"}]}, + } + ], + }, + "DefaultCacheBehavior": { + "TargetOriginId": "group", + "ViewerProtocolPolicy": "allow-all", + "DefaultTTL": "60", + "FunctionAssociations": [ + {"EventType": "viewer-request", "FunctionARN": "arn:fn"} + ], + "LambdaFunctionAssociations": [ + { + "EventType": "origin-request", + "LambdaFunctionARN": "arn:l", + "IncludeBody": "true", + }, + {"EventType": "origin-response", "LambdaFunctionARN": "arn:l2"}, + ], + "ForwardedValues": { + "Cookies": {"Forward": "whitelist", "WhitelistedNames": ["s"]} + }, + }, + "CacheBehaviors": [ + { + "PathPattern": "/x", + "TargetOriginId": "web", + "ViewerProtocolPolicy": "allow-all", + "ForwardedValues": {"QueryString": "false"}, + } + ], + "Restrictions": { + "GeoRestriction": {"RestrictionType": "whitelist", "Locations": ["DE"]} + }, + "ViewerCertificate": { + "AcmCertificateArn": "arn:cert", + "SslSupportMethod": "sni-only", + "MinimumProtocolVersion": "TLSv1.2_2021", + }, + }, + }, + }, + "Broken": { + "Type": "AWS::CloudFront::Distribution", + "Properties": {"DistributionConfig": {"Fn::If": ["C", {}, {}]}}, + }, + }, + conditions={"C": {"Fn::Equals": ["a", "b"]}}, + ) + assert 'resource "aws_cloudfront_origin_access_identity" "oai"' in hcl + assert 'comment = "site"' in hcl + assert ( + 'origin_access_identity = "origin-access-identity/cloudfront/' + '${aws_cloudfront_origin_access_identity.oai.id}"' in hcl + ) + assert any("OriginReadTimeout' has no Terraform counterpart" in n for n in notes) + assert 'custom_header { name = "X-A"' in hcl + assert "origin_shield {" in hcl and 'vpc_origin_id = "vo-1"' in hcl + assert 'origin_ssl_protocols = ["TLSv1.2"]' in hcl + assert any("had no OriginSSLProtocols" in n for n in notes) + assert "status_codes = [500, 502]" in hcl and hcl.count("member {") == 2 + assert "default_ttl = 60" in hcl + assert 'function_arn = "arn:fn"' in hcl and "include_body = true" in hcl + assert "query_string = false" in hcl + assert 'forward = "whitelist"' in hcl + assert 'forward = "none"' in hcl + assert 'locations = ["DE"]' in hcl + assert 'ssl_support_method = "sni-only"' in hcl + assert 'bucket = "logs.s3.amazonaws.com"' in hcl + assert any("Broken: DistributionConfig is missing or computed" in n for n in notes) + + +def test_origin_access_control_leftovers_are_noted(): + _, notes = convert( + { + "Oac": { + "Type": "AWS::CloudFront::OriginAccessControl", + "Properties": { + "OriginAccessControlConfig": { + "Name": "oac", + "OriginAccessControlOriginType": "s3", + "SigningBehavior": "always", + "SigningProtocol": "sigv4", + "Extra": True, + } + }, + } + } + ) + assert any("OriginAccessControlConfig.Extra" in n for n in notes) + + +def test_value_helpers_pass_through_non_literals(): + hcl, _ = convert( + { + "Tg": { + "Type": "AWS::ElasticLoadBalancingV2::TargetGroup", + "Properties": { + "HealthCheckEnabled": {"Ref": "On"}, + "HealthCheckIntervalSeconds": "often", + "TargetGroupAttributes": [ + {"Key": "preserve_client_ip.enabled", "Value": "true"} + ], + }, + }, + "Endpoint": { + "Type": "AWS::EC2::VPCEndpoint", + "Properties": { + "VpcId": "vpc-1", + "ServiceName": "s", + "SubnetIds": {"Fn::Split": [",", {"Ref": "Subnets"}]}, + "DnsOptions": {"DnsRecordIpType": "ipv4"}, + }, + }, + "Rule": { + "Type": "AWS::ElasticLoadBalancingV2::ListenerRule", + "Properties": { + "ListenerArn": "arn:l", + "Actions": [{"Type": "forward", "TargetGroupArn": "arn:tg"}], + "Conditions": [ + {"Field": "source-ip", "SourceIpConfig": {"Values": {"Fn::GetAZs": ""}}} + ], + }, + }, + }, + parameters={"On": {"Type": "String"}, "Subnets": {"Type": "String"}}, + ) + assert "enabled = var.on" in hcl and 'interval = "often"' in hcl + assert 'preserve_client_ip = "true"' in hcl + assert 'subnet_ids = split(",", var.subnets)' in hcl + assert "values = data.aws_availability_zones.available.names" in hcl + + +def test_refers_to_reference_forms(): + assert _refers_to({"Ref": "Sg"}, "Sg") + assert _refers_to({"Fn::GetAtt": "Sg.GroupId"}, "Sg") + assert _refers_to({"Fn::GetAtt": ["Sg", "GroupId"]}, "Sg") + assert not _refers_to("sg-123", "Sg") + assert not _refers_to({"Fn::GetAtt": []}, "Sg") + + +# --- regressions -------------------------------------------------------------------------- + +NO = {"Ref": "AWS::NoValue"} +ENV_PARAMETERS = {"Env": {"Type": "String"}} +ENV_CONDITIONS = {"On": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}} + + +def _if(yes: object, no: object = NO) -> dict: + return {"Fn::If": ["On", yes, no]} + + +def _group(props: dict) -> dict: + properties = {"GroupDescription": "d", "VpcId": "vpc-1"} + properties.update(props) + return {"Type": "AWS::EC2::SecurityGroup", "Properties": properties} + + +SSH = {"IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIp": "10.0.0.0/8"} +HTTPS = {"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443, "CidrIp": "0.0.0.0/0"} +ALLOW_ALL = 'from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"]' + + +def test_standalone_rules_from_optional_items_are_counted(): + hcl, notes = convert( + { + "Sg": _group({"SecurityGroupIngress": [_if(SSH), NO, _if(SSH, HTTPS)]}), + "Self": { + "Type": "AWS::EC2::SecurityGroupIngress", + "Properties": { + "GroupId": {"Ref": "Sg"}, + "IpProtocol": "-1", + "SourceSecurityGroupId": {"Ref": "Sg"}, + }, + }, + }, + parameters=ENV_PARAMETERS, + conditions=ENV_CONDITIONS, + ) + assert ( + 'resource "aws_vpc_security_group_ingress_rule" "sg_ingress_1" { count = local.on ? 1 : 0' + in hcl + ) + assert 'cidr_ipv4 = "10.0.0.0/8"' in hcl + assert "sg_ingress_2" not in hcl and "sg_ingress_3" not in hcl + assert "ingress[2] was not converted" in hcl + assert any("'Sg.ingress[2]' is computed by a function" in n for n in notes) + + +def test_default_egress_kept_when_the_egress_rules_are_optional(): + hcl, notes = convert( + { + "Inline": _group({"SecurityGroupEgress": _if([HTTPS])}), + "Single": _group({"SecurityGroupEgress": _if(HTTPS)}), + "Swapped": _group({"SecurityGroupEgress": _if(NO, [HTTPS])}), + "Computed": _group({"SecurityGroupEgress": _if([HTTPS], [SSH])}), + "Odd": _group({"SecurityGroupEgress": {"Fn::If": "odd"}}), + "Standalone": _group({"SecurityGroupEgress": _if([HTTPS])}), + "Rule": { + "Type": "AWS::EC2::SecurityGroupIngress", + "Properties": { + "GroupId": {"Ref": "Standalone"}, + "IpProtocol": "-1", + "CidrIp": "10.0.0.0/8", + }, + }, + }, + parameters=ENV_PARAMETERS, + conditions=ENV_CONDITIONS, + ) + inline = hcl.split('resource "aws_security_group" "inline"')[1].split('resource "')[0] + assert 'dynamic "egress" { for_each = local.on ? [1] : [] content { from_port = 443' in inline + assert f'dynamic "egress" {{ for_each = !local.on ? [1] : [] content {{ {ALLOW_ALL}' in inline + assert "CloudFormation adds this allow-all egress rule" in inline + single = hcl.split('resource "aws_security_group" "single"')[1].split('resource "')[0] + assert "for_each = !local.on ? [1] : []" in single + swapped = hcl.split('resource "aws_security_group" "swapped"')[1].split('resource "')[0] + assert "for_each = !local.on ? [1] : [] content { from_port = 443" in swapped + assert f"for_each = local.on ? [1] : [] content {{ {ALLOW_ALL}" in swapped + computed = hcl.split('resource "aws_security_group" "computed"')[1].split('resource "')[0] + assert "Egress was not converted" in computed + assert ( + 'resource "aws_vpc_security_group_egress_rule" "standalone_egress_1" ' + "{ count = local.on ? 1 : 0 security_group_id = aws_security_group.standalone.id " + 'ip_protocol = "tcp"' + ) in hcl + assert ( + 'resource "aws_vpc_security_group_egress_rule" "standalone_egress_2" { count = !local.on ' + "? 1 : 0 # CloudFormation adds this allow-all egress rule when the template has none; " + "# Terraform removes it, so it is written out. security_group_id = " + 'aws_security_group.standalone.id ip_protocol = "-1" cidr_ipv4 = "0.0.0.0/0" }' + ) in hcl + assert any("Computed.Egress' is computed by a function" in n for n in notes) + assert any("Odd.Egress' is computed by a function" in n for n in notes) + + +def _target_group(attributes: list, props: dict | None = None) -> dict: + properties = { + "Port": 80, + "Protocol": "HTTP", + "VpcId": "vpc-1", + "TargetGroupAttributes": [{"Key": k, "Value": v} for k, v in attributes], + } + properties.update(props or {}) + return {"Type": "AWS::ElasticLoadBalancingV2::TargetGroup", "Properties": properties} + + +def test_target_group_stickiness_defaults_and_cookie_durations(): + hcl, notes = convert( + { + "Lb": _target_group([("stickiness.lb_cookie.duration_seconds", "3600")]), + "App": _target_group( + [ + ("stickiness.enabled", "true"), + ("stickiness.type", "app_cookie"), + ("stickiness.app_cookie.cookie_name", "SESS"), + ("stickiness.app_cookie.duration_seconds", "600"), + ("stickiness.lb_cookie.duration_seconds", "3600"), + ] + ), + } + ) + assert 'stickiness { enabled = false cookie_duration = 3600 type = "lb_cookie" }' in hcl + assert ( + 'stickiness { enabled = true type = "app_cookie" cookie_name = "SESS" ' + "cookie_duration = 600 }" + ) in hcl + assert 'TargetGroupAttributes "stickiness.lb_cookie.duration_seconds" = "3600" was not' in hcl + assert any("'stickiness.lb_cookie.duration_seconds' was not converted" in n for n in notes) + + +def test_partial_health_check_gets_the_aws_thresholds(): + hcl, _ = convert( + { + "Web": _target_group([], {"HealthCheckPath": "/health"}), + "Tuned": _target_group([], {"HealthyThresholdCount": 3, "UnhealthyThresholdCount": 4}), + "Fn": { + "Type": "AWS::ElasticLoadBalancingV2::TargetGroup", + "Properties": {"TargetType": "lambda", "HealthCheckEnabled": True}, + }, + "Geneve": _target_group( + [], {"Protocol": "GENEVE", "Port": 6081, "HealthCheckPort": "80"} + ), + "Plain": _target_group([]), + } + ) + assert 'health_check { path = "/health" healthy_threshold = 5 unhealthy_threshold = 2 }' in hcl + assert "health_check { healthy_threshold = 3 unhealthy_threshold = 4 }" in hcl + assert ( + "health_check { enabled = true healthy_threshold = 5 unhealthy_threshold = 5 " + "interval = 35 }" + ) in hcl + assert "health_check" in hcl + assert 'port = "80" healthy_threshold = 5 unhealthy_threshold = 2 interval = 10 }' in hcl + assert hcl.count("health_check {") == 4 + + +def test_forward_config_stickiness_is_kept(): + hcl, notes = convert( + { + "Listener": { + "Type": "AWS::ElasticLoadBalancingV2::Listener", + "Properties": { + "LoadBalancerArn": "arn:lb", + "Port": 80, + "Protocol": "HTTP", + "DefaultActions": [ + { + "Type": "forward", + "TargetGroupArn": "arn:tg", + "ForwardConfig": { + "TargetGroups": [{"TargetGroupArn": "arn:tg"}], + "TargetGroupStickinessConfig": { + "Enabled": True, + "DurationSeconds": 300, + }, + }, + } + ], + }, + } + } + ) + assert ( + 'default_action { type = "forward" forward { target_group { arn = "arn:tg" } ' + "stickiness { enabled = true duration = 300 } } }" + ) in hcl + assert "target_group_arn" not in hcl + assert notes == [] + + +def test_lists_from_functions_do_not_crash(): + lambda_arn = "arn:aws:lambda:us-east-1:123456789012:function:f:1" + hcl, notes = convert( + { + "Dist": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "Enabled": True, + "Origins": [ + { + "Id": "web", + "DomainName": "example.com", + "OriginCustomHeaders": _if( + [{"HeaderName": "X", "HeaderValue": "1"}] + ), + "CustomOriginConfig": { + "OriginProtocolPolicy": "https-only", + "OriginSSLProtocols": ["TLSv1.2"], + }, + }, + { + "Id": "b", + "DomainName": "b.example.com", + "S3OriginConfig": {"Ref": "S3"}, + }, + ], + "OriginGroups": { + "Quantity": 2, + "Items": [ + { + "Id": "g", + "FailoverCriteria": {"StatusCodes": {"Ref": "Codes"}}, + "Members": {"Quantity": 1, "Items": {"Ref": "Members"}}, + }, + { + "Id": "h", + "FailoverCriteria": { + "StatusCodes": {"Quantity": 1, "Items": [500]} + }, + "Members": {"Quantity": 1, "Items": [{"OriginId": "web"}]}, + }, + ], + }, + "DefaultCacheBehavior": { + "TargetOriginId": "web", + "ViewerProtocolPolicy": "allow-all", + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + "LambdaFunctionAssociations": _if( + [{"EventType": "viewer-request", "LambdaFunctionARN": lambda_arn}] + ), + "FunctionAssociations": {"Ref": "Functions"}, + }, + } + }, + }, + "Rule": { + "Type": "AWS::ElasticLoadBalancingV2::ListenerRule", + "Properties": { + "ListenerArn": "arn:listener", + "Priority": 1, + "Conditions": [ + { + "Field": "query-string", + "QueryStringConfig": {"Values": {"Ref": "Query"}}, + }, + { + "Field": "query-string", + "QueryStringConfig": {"Values": [{"Value": "v"}]}, + }, + {"Field": "host-header", "HostHeaderConfig": {"Ref": "Hosts"}}, + ], + "Actions": [ + { + "Type": "forward", + "ForwardConfig": { + "TargetGroups": _if( + [{"TargetGroupArn": "arn:a"}], [{"TargetGroupArn": "arn:b"}] + ) + }, + } + ], + }, + }, + }, + parameters={ + name: {"Type": "String"} + for name in ("Env", "S3", "Codes", "Members", "Functions", "Query", "Hosts") + }, + conditions=ENV_CONDITIONS, + ) + assert ( + 'dynamic "custom_header" { for_each = local.on ? [1] : [] content { name = "X" ' + 'value = "1" } }' + ) in hcl + assert "custom_header" in hcl + assert ( + 'dynamic "lambda_function_association" { for_each = local.on ? [1] : [] content { ' + f'event_type = "viewer-request" lambda_arn = "{lambda_arn}" }} }}' + ) in hcl + assert 'query_string { value = "v" }' in hcl + assert 'failover_criteria { status_codes = [500] } member { origin_id = "web" }' in hcl + for text in ( + "FunctionAssociations was not converted", + "S3OriginConfig was not converted", + "StatusCodes was not converted", + "Members.Items was not converted", + "Values was not converted", + "HostHeaderConfig was not converted", + "TargetGroups was not converted", + ): + assert text in hcl + assert any("computed by a function" in n for n in notes) + + +def test_distribution_http_version_and_zone_comment_defaults(): + hcl, _ = convert( + { + "Dist": { + "Type": "AWS::CloudFront::Distribution", + "Properties": { + "DistributionConfig": { + "Enabled": True, + "Origins": [ + {"Id": "web", "DomainName": "example.com", "S3OriginConfig": {}} + ], + "DefaultCacheBehavior": { + "TargetOriginId": "web", + "ViewerProtocolPolicy": "allow-all", + "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6", + }, + } + }, + }, + "Zone": {"Type": "AWS::Route53::HostedZone", "Properties": {"Name": "example.com"}}, + } + ) + assert 'http_version = "http1.1"' in hcl + assert 'resource "aws_route53_zone" "zone" { name = "example.com" comment = "" }' in hcl + + +def test_load_balancer_scheme_from_a_condition_is_compared_whole(): + hcl, _ = convert( + { + "Lb": { + "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer", + "Properties": { + "Scheme": _if("internal", "internet-facing"), + "Subnets": ["subnet-1"], + }, + } + }, + parameters=ENV_PARAMETERS, + conditions=ENV_CONDITIONS, + ) + assert 'internal = (local.on ? "internal" : "internet-facing") == "internal"' in hcl + + +PAYLOAD = ( + 'x"\n}\nresource "terraform_data" "pwn" {\n provisioner "local-exec" { command = "id" }\n' + '}\n# ${file("/etc/passwd")}\r' +) + + +def _assert_inert(content: str) -> None: + """No line of the payload became HCL: every injected line is inside a quoted string or a + comment, and `${` outside comments is escaped as `$${`.""" + for line in content.split("\n"): + code = line.strip() + if code.startswith("#"): + continue + assert not code.startswith(('resource "terraform_data"', "provisioner")) + assert line.replace("$${", "").count("${file") == 0, line + + +def test_template_text_cannot_inject_hcl(): + """Strings from the template end up quoted and escaped, also in comments and names.""" + template = { + "Resources": { + "Tg": _target_group([(PAYLOAD, "1"), ("stickiness.type", PAYLOAD)]), + "Rule": { + "Type": "AWS::ElasticLoadBalancingV2::ListenerRule", + "Properties": { + "ListenerArn": "arn:listener", + "Priority": 1, + "Conditions": [ + {"Field": PAYLOAD}, + { + "Field": "query-string", + "QueryStringConfig": {"Values": [{"Key": PAYLOAD, "Value": PAYLOAD}]}, + }, + ], + "Actions": [{"Type": "forward", "TargetGroupArn": PAYLOAD}], + }, + }, + "Db": { + "Type": "AWS::RDS::DBInstance", + "Properties": { + "Engine": "postgres", + "DBInstanceClass": "db.t4g.micro", + "DBInstanceIdentifier": PAYLOAD, + }, + }, + "Member": { + "Type": "AWS::RDS::DBInstance", + "Properties": { + "Engine": "aurora-postgresql", + "DBInstanceClass": "db.serverless", + "DBClusterIdentifier": PAYLOAD, + "DBInstanceIdentifier": {"Fn::Sub": PAYLOAD.replace("${", "${!")}, + }, + }, + "Params": { + "Type": "AWS::RDS::DBParameterGroup", + "Properties": { + "Family": "postgres16", + "Description": PAYLOAD, + "DBParameterGroupName": PAYLOAD, + "Parameters": {PAYLOAD: PAYLOAD}, + }, + }, + "Cert": { + "Type": "AWS::CertificateManager::Certificate", + "Properties": { + "DomainName": PAYLOAD, + "ValidationMethod": "DNS", + "DomainValidationOptions": [ + {"DomainName": PAYLOAD, "HostedZoneId": "Z1"}, + {"DomainName": "b" + PAYLOAD, "HostedZoneId": PAYLOAD}, + ], + }, + }, + "Record": { + "Type": "AWS::Route53::RecordSet", + "Properties": {"HostedZoneName": PAYLOAD, "Name": PAYLOAD, "Type": "A", "TTL": 60}, + }, + "Machine": { + "Type": "AWS::StepFunctions::StateMachine", + "Properties": { + "RoleArn": "arn:role", + "Definition": {"StartAt": PAYLOAD, "States": {PAYLOAD: {"Comment": "${Name}"}}}, + "DefinitionSubstitutions": {"Name": PAYLOAD}, + }, + }, + "Policy": { + "Type": "AWS::IAM::Policy", + "Properties": { + "PolicyName": PAYLOAD, + "PolicyDocument": {"Statement": [{"Sid": PAYLOAD}]}, + "Roles": [PAYLOAD, {"Fn::If": ["On", PAYLOAD, NO]}], + }, + }, + "Alarm": { + "Type": "AWS::CloudWatch::Alarm", + "Properties": { + "AlarmName": PAYLOAD, + "ComparisonOperator": "GreaterThanThreshold", + "EvaluationPeriods": 1, + "Threshold": 1, + "MetricName": PAYLOAD, + "Namespace": PAYLOAD, + "Period": 60, + "Statistic": "Sum", + "Dimensions": [{"Name": PAYLOAD, "Value": PAYLOAD}], + }, + }, + }, + "Parameters": ENV_PARAMETERS, + "Conditions": ENV_CONDITIONS, + } + result = convert_template(yaml.safe_dump(template, sort_keys=False), stack_name="demo") + for file in result["files"]: + _assert_inert(file["content"]) diff --git a/services/converter-api/tests/test_cfn_observability.py b/services/converter-api/tests/test_cfn_observability.py new file mode 100644 index 0000000..d6d06ca --- /dev/null +++ b/services/converter-api/tests/test_cfn_observability.py @@ -0,0 +1,224 @@ +"""CloudWatch Logs, alarm and dashboard mappings.""" + +from __future__ import annotations + +import json +import re + +from converters.cfn.pipeline import convert_template + +NO = {"Ref": "AWS::NoValue"} + + +def convert( + resources: dict, + parameters: dict | None = None, + conditions: dict | None = None, + outputs: dict | None = None, +) -> tuple[str, list[str]]: + template: dict = {"Resources": resources} + for section, value in ( + ("Parameters", parameters), + ("Conditions", conditions), + ("Outputs", outputs), + ): + if value is not None: + template[section] = value + result = convert_template(json.dumps(template), stack_name="demo") + files = {f["path"]: f["content"] for f in result["files"]} + return files["main.tf"] + files.get("outputs.tf", ""), result["notes"] + + +def test_log_group_arn_keeps_the_stream_wildcard_also_when_conditional(): + main, _ = convert( + { + "Logs": { + "Type": "AWS::Logs::LogGroup", + "Condition": "On", + "Properties": {"KmsKeyId": "k"}, + } + }, + conditions={"On": {"Fn::Equals": [1, 1]}}, + outputs={ + "Arn": {"Value": {"Fn::GetAtt": ["Logs", "Arn"]}, "Condition": "On"}, + "Name": {"Value": {"Ref": "Logs"}, "Condition": "On"}, + }, + ) + assert '"${aws_cloudwatch_log_group.logs[0].arn}:*"' in main + assert "aws_cloudwatch_log_group.logs[0].name" in main + + +def test_metric_filter_values_and_dimensions(): + main, notes = convert( + { + "Filter": { + "Type": "AWS::Logs::MetricFilter", + "Properties": { + "FilterName": "f", + "LogGroupName": "/g", + "FilterPattern": "x", + "ApplyOnTransformedLogs": "false", + "MetricTransformations": [ + { + "MetricName": "M", + "MetricNamespace": "N", + "MetricValue": "1", + "DefaultValue": {"Ref": "Default"}, + "Dimensions": {"Fn::If": ["On", [], []]}, + } + ], + }, + } + }, + parameters={"Default": {"Type": "String"}}, + conditions={"On": {"Fn::Equals": [1, 1]}}, + outputs={"Name": {"Value": {"Ref": "Filter"}}}, + ) + assert "default_value = var.default" in main + assert "apply_on_transformed_logs = false" in main + assert "dimensions = { for tag in local.on ? [] : [] : tag.Key => tag.Value }" in main + assert "aws_cloudwatch_log_metric_filter.filter.name" in main + assert not [n for n in notes if "not converted" in n] + + +def test_subscription_filter(): + main, notes = convert( + { + "Sub": { + "Type": "AWS::Logs::SubscriptionFilter", + "Properties": { + "LogGroupName": "/g", + "FilterPattern": "", + "DestinationArn": "arn:aws:lambda:us-east-1:1:function:f", + "EmitSystemFields": "@aws.region", + }, + } + } + ) + assert 'name = "${var.stack_name}-Sub"' in main + assert 'emit_system_fields = ["@aws.region"]' in main + assert any("Sub had no FilterName" in n for n in notes) + + +def test_alarm_metric_queries_and_dimension_maps(): + main, _ = convert( + { + "Alarm": { + "Type": "AWS::CloudWatch::Alarm", + "Properties": { + "AlarmName": "a", + "ComparisonOperator": "GreaterThanThreshold", + "EvaluationPeriods": 1, + "Threshold": 1, + "ThresholdMetricId": "band", + "Metrics": [ + {"Id": "band", "Expression": "ANOMALY_DETECTION_BAND(m, 2)"}, + {"Id": "m", "AccountId": "123456789012", "Period": 60, "MetricStat": "x"}, + { + "Id": "n", + "MetricStat": {"Metric": {}, "Period": 60, "Stat": "Sum"}, + }, + ], + }, + }, + "Mapped": { + "Type": "AWS::CloudWatch::Alarm", + "Properties": { + "AlarmName": "b", + "ComparisonOperator": "LessThanThreshold", + "EvaluationPeriods": 1, + "Threshold": 1, + "Dimensions": {"Service": "app"}, + }, + }, + }, + outputs={"Name": {"Value": {"Ref": "Alarm"}}}, + ) + assert 'threshold_metric_id = "band"' in main + assert 'account_id = "123456789012"' in main + assert "metric {\n period = 60" in main + assert 'dimensions = {\n Service = "app"\n }' in main + assert "aws_cloudwatch_metric_alarm.alarm.alarm_name" in main + + +def test_dashboard_body_forms(): + main, notes = convert( + { + "Text": { + "Type": "AWS::CloudWatch::Dashboard", + "Properties": { + "DashboardName": "t", + "DashboardBody": {"Fn::Sub": "not json ${AWS::Region}"}, + }, + }, + "Joined": { + "Type": "AWS::CloudWatch::Dashboard", + "Properties": { + "DashboardName": "j", + "DashboardBody": {"Fn::Join": ["", ['{"widgets":', "[]}"]]}, + }, + }, + }, + outputs={"Name": {"Value": {"Ref": "Text"}}}, + ) + assert 'dashboard_body = "not json ${data.aws_region.current.region}"' in main + assert 'dashboard_body = "{\\"widgets\\":[]}"' in main + assert "aws_cloudwatch_dashboard.text.dashboard_name" in main + assert notes == [] + + +def test_alarm_actions_drop_novalue_items(): + main, notes = convert( + { + "Alarm": { + "Type": "AWS::CloudWatch::Alarm", + "Properties": { + "AlarmName": "a", + "ComparisonOperator": "GreaterThanThreshold", + "EvaluationPeriods": 1, + "Threshold": 1, + "MetricName": "Errors", + "Namespace": "App", + "Period": 60, + "Statistic": "Sum", + "AlarmActions": [ + {"Fn::If": ["On", "arn:aws:sns:us-east-1:123456789012:t", NO]}, + "arn:aws:sns:us-east-1:123456789012:u", + ], + "OKActions": [NO], + }, + } + }, + parameters={"Env": {"Type": "String"}}, + conditions={"On": {"Fn::Equals": [{"Ref": "Env"}, "prod"]}}, + ) + assert ( + 'alarm_actions = [for item in [local.on ? "arn:aws:sns:us-east-1:123456789012:t" : null,' + ' "arn:aws:sns:us-east-1:123456789012:u"] : item if item != null]' + ) in re.sub(r" +=", " =", main) + assert "ok_actions" in main and "[null]" not in main + + +def test_alarm_metric_stat_from_a_function_is_reported(): + main, notes = convert( + { + "Alarm": { + "Type": "AWS::CloudWatch::Alarm", + "Properties": { + "AlarmName": "a", + "ComparisonOperator": "GreaterThanThreshold", + "EvaluationPeriods": 1, + "Threshold": 1, + "Metrics": [ + {"Id": "m1", "MetricStat": {"Ref": "Stat"}}, + {"Id": "m2", "MetricStat": {"Metric": {"Ref": "Metric"}, "Stat": "Sum"}}, + ], + }, + } + }, + parameters={"Stat": {"Type": "String"}, "Metric": {"Type": "String"}}, + ) + assert "MetricStat was not converted" in main + assert "Metric was not converted" in main + assert any("Alarm.Metrics[0].MetricStat' is computed" in n for n in notes) + assert any("Alarm.Metrics[1].MetricStat.Metric' is computed" in n for n in notes) diff --git a/services/converter-api/tests/test_cfn_review_fixes.py b/services/converter-api/tests/test_cfn_review_fixes.py new file mode 100644 index 0000000..2a3cad8 --- /dev/null +++ b/services/converter-api/tests/test_cfn_review_fixes.py @@ -0,0 +1,301 @@ +"""Regression tests for problems found in review: HCL injection, input limits, and +expressions that were valid HCL but meant something else.""" + +from __future__ import annotations + +import json +import re + +import pytest +import yaml + +from converters.cfn.context import Context +from converters.cfn.errors import CfnError +from converters.cfn.naming import UniqueNames +from converters.cfn.parse import load_template +from converters.cfn.pipeline import convert_template + +BUCKET = {"Bucket": {"Type": "AWS::S3::Bucket"}} +NO_VALUE = {"Ref": "AWS::NoValue"} +FALSE = {"C": {"Fn::Equals": ["a", "b"]}} + + +def files(template: dict) -> dict[str, str]: + result = convert_template(yaml.safe_dump(template, sort_keys=False)) + return {f["path"]: re.sub(r" +", " ", f["content"]) for f in result["files"]} + + +def expression(value, template: dict | None = None) -> str: + template = dict(template or {}) + template.setdefault("Resources", dict(BUCKET)) + template["Outputs"] = {"Out": {"Value": value}} + out = files(template)["outputs.tf"] + return out.split("value = ", 1)[1].rsplit("\n}", 1)[0] + + +# --- injection --------------------------------------------------------------------------- + +INJECTION = '"\n}\nresource "terraform_data" "pwn" {\n' + + +@pytest.mark.parametrize( + ("section", "name"), + [ + ("Resources", "U" + INJECTION), + ("Resources", "Bad-Name"), + ("Parameters", "a.b"), + ("Conditions", "x y"), + ("Mappings", "${x}"), + ("Outputs", "${x}"), + ], +) +def test_names_must_be_alphanumeric(section, name): + template: dict = {"Resources": dict(BUCKET)} + entry = { + "Resources": {"Type": "AWS::S3::Bucket"}, + "Parameters": {"Type": "String"}, + "Conditions": {"Fn::Equals": ["a", "a"]}, + "Mappings": {"k": {"v": 1}}, + "Outputs": {"Value": "x"}, + }[section] + template.setdefault(section, {})[name] = entry + with pytest.raises(CfnError, match="letters and digits only"): + load_template(json.dumps(template)) + + +def test_get_att_attribute_names_are_checked(): + with pytest.raises(CfnError, match="is invalid"): + expression({"Fn::GetAtt": ["Bucket", 'Arn"} {"']}) + + +def test_sam_definition_uri_is_escaped(): + template = { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Api": { + "Type": "AWS::Serverless::Api", + "Properties": {"StageName": "s", "DefinitionUri": 'a"${file("x")}.yaml'}, + } + }, + } + main = files(template)["main.tf"] + assert 'file("${path.module}/a\\"$${file(\\"x\\")}.yaml")' in main + assert "terraform_data" not in main + + +# --- limits ------------------------------------------------------------------------------ + + +def test_non_finite_numbers_and_huge_cidr_counts_are_rejected(): + with pytest.raises(CfnError, match="Invalid number"): + load_template("Resources: {B: {Type: X, Properties: {V: 1.0e400}}}") + with pytest.raises(CfnError, match="Invalid number"): + load_template('{"Resources": {"B": {"Type": "X", "Properties": {"V": 1e400}}}}') + with pytest.raises(CfnError, match="at most 256"): + expression({"Fn::Cidr": ["::/0", 1_000_000, 1]}) + + +def test_many_colliding_names_stay_linear(): + names = UniqueNames() + taken = [names.take("a") for _ in range(20_000)] + assert taken[-1] == "a_20000" and len(set(taken)) == 20_000 + + +def test_json_strings_too_deep_or_recursive(): + ctx = Context({"Resources": {}}) + assert ctx.json("[" * 100_000) == "[" * 100_000 + with pytest.raises(CfnError, match="nested too deeply"): + ctx.json("[" * 150 + "]" * 150) + + +# --- template strings -------------------------------------------------------------------- + + +def test_template_strings_escape_across_pieces(): + template = {"Parameters": {"N": {"Type": "String"}}} + assert expression({"Fn::Sub": "$${N}"}, template) == '"${"$"}${var.n}"' + assert expression({"Fn::Join": ["", ["$", "{path.cwd}", {"Ref": "N"}]]}, template) == ( + '"$${path.cwd}${var.n}"' + ) + assert expression({"Fn::Join": ["", ["100%", {"Ref": "N"}]]}, template) == ( + '"100${"%"}${var.n}"' + ) + assert expression({"Fn::Join": ["-", ["a", True, 1.5]]}) == '"a-true-1.5"' + assert expression({"Fn::Join": ["-", ["a", NO_VALUE, "b"]]}) == '"a-b"' + assert expression({"Fn::Join": ["-", []]}) == '""' + + +def test_join_with_optional_items_filters_them(): + value = {"Fn::Join": ["-", ["jobs", {"Fn::If": ["C", "prod", NO_VALUE]}]]} + assert expression(value, {"Conditions": FALSE}) == ( + 'join("-", [for item in ["jobs", local.c ? "prod" : null] : item if item != null])' + ) + + +# --- conditions and NoValue -------------------------------------------------------------- + + +def test_equals_compares_as_text(): + template = { + "Parameters": {"N": {"Type": "Number"}, "Flag": {"Type": "String"}}, + "Conditions": { + "IsTwo": {"Fn::Equals": [{"Ref": "N"}, 2]}, + "On": {"Fn::Equals": [{"Ref": "Flag"}, True]}, + }, + "Resources": BUCKET, + } + locals_tf = files(template)["locals.tf"] + assert 'is_two = tostring(var.n) == "2"' in locals_tf + assert 'on = var.flag == "true"' in locals_tf + + +def test_mappings_drop_optional_keys(): + value = {"A": "1", "B": {"Fn::If": ["C", "2", NO_VALUE]}, "N": NO_VALUE} + assert expression(value, {"Conditions": FALSE}) == ( + 'merge({ A = "1" }, local.c ? { B = "2" } : {})' + ) + + +def test_if_inside_json_documents(): + template = { + "Conditions": FALSE, + "Resources": { + "P": { + "Type": "AWS::SQS::QueuePolicy", + "Properties": { + "Queues": ["https://q"], + "PolicyDocument": { + "Statement": [ + { + "Action": {"Fn::If": ["C", "sqs:A", ["sqs:A", "sqs:B"]]}, + "Resource": "*", + } + ] + }, + }, + }, + "Q": { + "Type": "AWS::SQS::Queue", + "Properties": { + "RedrivePolicy": { + "Fn::If": [ + "C", + {"deadLetterTargetArn": "arn", "maxReceiveCount": 3}, + NO_VALUE, + ] + } + }, + }, + }, + } + main = files(template)["main.tf"] + assert ( + 'Action = jsondecode(local.c ? jsonencode("sqs:A") : jsonencode(["sqs:A", "sqs:B"]))' + in main + ) + assert ( + 'redrive_policy = local.c ? jsonencode({ deadLetterTargetArn = "arn", ' + "maxReceiveCount = 3 }) : null" in main + ) + + +def test_awscc_lists_drop_optional_items(): + template = { + "Conditions": FALSE, + "Resources": { + "Q": { + "Type": "AWS::Batch::JobQueue", + "Properties": { + "Priority": 1, + "ComputeEnvironmentOrder": [ + {"Order": 1, "ComputeEnvironment": "a"}, + {"Fn::If": ["C", {"Order": 2, "ComputeEnvironment": "b"}, NO_VALUE]}, + NO_VALUE, + ], + }, + } + }, + } + main = files(template)["main.tf"] + assert "compute_environment_order = [for item in [" in main + assert 'local.c ? { order = 2, compute_environment = "b" } : null' in main + + +# --- names, sensitivity, SAM --------------------------------------------------------------- + + +def test_extra_resources_never_collide_with_converted_ones(): + template = { + "Resources": { + "Alerts": { + "Type": "AWS::SNS::Topic", + "Properties": {"Subscription": [{"Protocol": "email", "Endpoint": "a@b.c"}]}, + }, + "AlertsSubscription": { + "Type": "AWS::SNS::Subscription", + "Properties": { + "Protocol": "email", + "Endpoint": "x@y.z", + "TopicArn": {"Ref": "Alerts"}, + }, + }, + } + } + main = files(template)["main.tf"] + names = re.findall(r'resource "aws_sns_topic_subscription" "(\w+)"', main) + assert len(names) == 2 and len(set(names)) == 2 + + +def test_outputs_using_a_condition_built_from_a_secret_are_sensitive(): + template = { + "Parameters": {"Pw": {"Type": "String", "NoEcho": "true"}}, + "Conditions": { + "HasPw": {"Fn::Not": [{"Fn::Equals": [{"Ref": "Pw"}, ""]}]}, + "AlsoPw": {"Fn::And": [{"Condition": "HasPw"}, {"Fn::Equals": ["a", "a"]}]}, + }, + "Resources": BUCKET, + "Outputs": { + "Arn": {"Condition": "AlsoPw", "Value": {"Fn::GetAtt": ["Bucket", "Arn"]}}, + "Plain": {"Value": {"Ref": "Bucket"}}, + }, + } + outputs = files(template)["outputs.tf"] + arn, plain = outputs.split('output "plain"') + assert "sensitive = true" in arn and "sensitive" not in plain + + +def test_sam_vpc_policy_api_globals_and_stage_references_in_sub(): + template = { + "Transform": "AWS::Serverless-2016-10-31", + "Globals": { + "Api": {"EndpointConfiguration": "REGIONAL", "BinaryMediaTypes": ["image/png"]} + }, + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "a.b", + "Runtime": "python3.13", + "InlineCode": "x", + "VpcConfig": {"SubnetIds": ["s"], "SecurityGroupIds": ["g"]}, + "Events": { + "Get": {"Type": "Api", "Properties": {"Path": "/", "Method": "get"}} + }, + }, + }, + "MyApi": {"Type": "AWS::Serverless::Api", "Properties": {"StageName": "v1"}}, + }, + "Outputs": { + "Url": {"Value": {"Fn::Sub": "https://${MyApi}.execute-api/${MyApi.Stage}/"}}, + "Other": {"Value": {"Fn::Sub": ["${MyApi.Stage}-${X}", {"X": "y"}]}}, + }, + } + out = files(template) + main = out["main.tf"] + assert "AWSLambdaVPCAccessExecutionRole" in main + rest = main.split('resource "aws_api_gateway_rest_api" "serverless_rest_api"')[1] + assert 'types = ["REGIONAL"]' in rest.split("\n}\n")[0] + assert '"image/png"' in rest.split("\n}\n")[0] + outputs = out["outputs.tf"] + assert "aws_api_gateway_stage.my_apiv1_stage.stage_name" in outputs + assert ".stage}" not in outputs diff --git a/services/converter-api/tests/test_cfn_sam.py b/services/converter-api/tests/test_cfn_sam.py new file mode 100644 index 0000000..acc27ec --- /dev/null +++ b/services/converter-api/tests/test_cfn_sam.py @@ -0,0 +1,871 @@ +"""AWS SAM expansion (converters/cfn/sam.py).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +import yaml + +from converters.cfn.errors import CfnError +from converters.cfn.models import Expression +from converters.cfn.pipeline import convert_template +from converters.cfn.sam import expand_sam +from converters.cfn.sam_policies import PolicyTemplates + +FIXTURE = Path(__file__).parent / "fixtures" / "cfn" / "sam.yaml" +TRANSFORM = "AWS::Serverless-2016-10-31" + + +def expand(resources: dict, extra: dict | None = None) -> tuple[dict, dict, list[str]]: + notes: list[str] = [] + template = {"Transform": TRANSFORM, "Resources": resources} + template.update(extra or {}) + out, hints = expand_sam(template, notes) + return out, hints, notes + + +def function(props: dict | None = None) -> dict: + properties = {"Handler": "a.b"} + properties.update(props or {}) + return {"Type": "AWS::Serverless::Function", "Properties": properties} + + +def with_attributes(resource: dict, attributes: dict) -> dict: + out = dict(resource) + out.update(attributes) + return out + + +def test_fixture_converts_to_aws_resources_only(): + result = convert_template(FIXTURE.read_text(), stack_name="demo") + assert result["source"] == "sam" + assert result["summary"]["awscc"] == 0 and result["summary"]["unsupported"] == 0 + assert not [n for n in result["notes"] if "was not converted" in n] + + +def test_function_role_and_globals(): + out, hints, notes = expand( + { + "Fn": function( + { + "CodeUri": "./src/", + "Environment": {"Variables": {"B": "2"}}, + "Layers": ["own"], + "Tags": {"team": "a"}, + "Tracing": "Active", + "Unknown": 1, + }, + ) + }, + { + "Globals": { + "Function": { + "Runtime": "python3.13", + "Environment": {"Variables": {"A": "1"}}, + "Layers": ["global"], + "Tags": {"Ref": "AWS::NoValue"}, + } + } + }, + ) + fn = out["Resources"]["Fn"] + assert fn["Type"] == "AWS::Lambda::Function" + props = fn["Properties"] + assert props["Runtime"] == "python3.13" + assert props["Environment"] == {"Variables": {"A": "1", "B": "2"}} + assert props["Layers"] == ["global", "own"] + assert props["Tags"] == [{"Key": "team", "Value": "a"}] + assert props["TracingConfig"] == {"Mode": "Active"} + assert props["Role"] == {"Fn::GetAtt": ["FnRole", "Arn"]} + assert hints == {"Fn": {"code_path": "src"}} + role = out["Resources"]["FnRole"]["Properties"] + assert len(role["ManagedPolicyArns"]) == 2 # basic execution + X-Ray + assert "Globals" not in out and "Transform" not in out + assert "Fn: SAM property 'Unknown' was not converted" in notes + + +@pytest.mark.parametrize( + ("props", "code", "hint"), + [ + ({"ImageUri": "repo:tag"}, {"ImageUri": "repo:tag"}, None), + ({"InlineCode": "x"}, {"ZipFile": "x"}, None), + ( + {"CodeUri": {"Bucket": "b", "Key": "k", "Version": "v"}}, + {"S3Bucket": "b", "S3Key": "k", "S3ObjectVersion": "v"}, + None, + ), + ({"CodeUri": "s3://b/path/k.zip"}, {"S3Bucket": "b", "S3Key": "path/k.zip"}, None), + ({"CodeUri": "."}, None, "."), + ({"CodeUri": "./"}, None, "."), + ], +) +def test_code_locations(props, code, hint): + out, hints, _ = expand({"Fn": function(props)}) + assert out["Resources"]["Fn"]["Properties"].get("Code") == code + assert hints.get("Fn", {}).get("code_path") == hint + + +def test_computed_code_uri_is_noted(): + _, _, notes = expand({"Fn": function({"CodeUri": {"Ref": "Path"}})}) + assert any("CodeUri is computed" in n for n in notes) + + +def test_dead_letter_queue_and_role_options(): + out, _, _ = expand( + { + "Sqs": function({"DeadLetterQueue": {"Type": "SQS", "TargetArn": "arn:q"}}), + "Sns": function( + { + "DeadLetterQueue": {"Type": "SNS", "TargetArn": "arn:t"}, + "PermissionsBoundary": "arn:boundary", + "RolePath": "/apps/", + "AssumeRolePolicyDocument": {"Statement": []}, + }, + ), + } + ) + sqs_role = out["Resources"]["SqsRole"]["Properties"] + assert sqs_role["Policies"][0]["PolicyDocument"]["Statement"][0]["Action"] == [ + "sqs:SendMessage" + ] + sns_role = out["Resources"]["SnsRole"]["Properties"] + assert sns_role["Policies"][0]["PolicyDocument"]["Statement"][0]["Action"] == ["sns:Publish"] + assert sns_role["PermissionsBoundary"] == "arn:boundary" + assert sns_role["Path"] == "/apps/" + assert sns_role["AssumeRolePolicyDocument"] == {"Statement": []} + + +def test_explicit_role_skips_the_generated_role(): + out, _, notes = expand( + {"Fn": function({"Role": "arn:role", "Policies": ["AmazonS3ReadOnlyAccess"]})} + ) + assert "FnRole" not in out["Resources"] + assert out["Resources"]["Fn"]["Properties"]["Role"] == "arn:role" + assert any("sets both Role and Policies" in n for n in notes) + + +def test_policies(): + out, _, notes = expand( + { + "Fn": function( + { + "Policies": [ + "AmazonS3ReadOnlyAccess", + "arn:aws:iam::aws:policy/Custom", + {"Ref": "PolicyArn"}, + {"Statement": {"Effect": "Allow", "Action": "s3:*", "Resource": "*"}}, + {"DynamoDBCrudPolicy": {"TableName": "t"}}, + {"NoSuchTemplate": {}}, + {"CloudWatchPutMetricPolicy": None}, + 42, + ] + } + ) + } + ) + role = out["Resources"]["FnRole"]["Properties"] + managed = role["ManagedPolicyArns"] + assert {"Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/AmazonS3ReadOnlyAccess"} in managed + assert "arn:aws:iam::aws:policy/Custom" in managed + assert {"Ref": "PolicyArn"} in managed + names = [p["PolicyName"] for p in role["Policies"]] + assert names == ["FnRolePolicy3", "FnRolePolicyTemplates"] + statements = role["Policies"][1]["PolicyDocument"]["Statement"] + assert statements[0]["Action"][0] == "dynamodb:GetItem" + assert statements[1]["Action"] == ["cloudwatch:PutMetricData"] + assert any("'NoSuchTemplate' was not converted" in n for n in notes) + assert any("a Policies entry was not converted" in n for n in notes) + + +@pytest.mark.parametrize("name", PolicyTemplates().names()) +def test_every_policy_template_converts(name): + params = { + "TableName": {"Ref": "T"}, + "StreamName": "s", + "BucketName": "b", + "QueueName": "q", + "TopicName": "t", + "FunctionName": "f", + "StateMachineName": "m", + "EventBusName": "e", + "ParameterName": "p", + "SecretArn": "arn:secret", + "KeyId": "k", + "LogGroupName": "l", + } + resources = { + "T": {"Type": "AWS::DynamoDB::Table", "Properties": {"TableName": "t"}}, + "Fn": function({"InlineCode": "x", "Runtime": "python3.13", "Policies": [{name: params}]}), + } + result = convert_template( + yaml.safe_dump({"Transform": TRANSFORM, "Resources": resources}), stack_name="demo" + ) + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + assert "_policy_templates" in main + + +def test_polling_and_rule_events(): + out, _, _ = expand( + { + "Fn": function( + { + "Events": { + "Queue": {"Type": "SQS", "Properties": {"Queue": "arn:q", "BatchSize": 5}}, + "Stream": { + "Type": "Kinesis", + "Properties": {"Stream": "arn:k", "StartingPosition": "LATEST"}, + }, + "Every": { + "Type": "Schedule", + "Properties": { + "Schedule": "rate(1 hour)", + "Enabled": False, + "Name": "n", + "Input": "{}", + }, + }, + "Bus": { + "Type": "EventBridgeRule", + "Properties": { + "Pattern": {"source": ["x"]}, + "EventBusName": "b", + "State": "ENABLED", + "RuleName": "r", + "Description": "d", + "InputPath": "$.x", + }, + }, + "Later": { + "Type": "ScheduleV2", + "Properties": { + "ScheduleExpression": "rate(1 day)", + "Name": "s", + "Input": "{}", + }, + }, + } + } + ) + } + ) + resources = out["Resources"] + assert resources["FnQueue"]["Properties"] == { + "EventSourceArn": "arn:q", + "FunctionName": {"Fn::GetAtt": ["Fn", "Arn"]}, + "BatchSize": 5, + } + every = resources["FnEvery"]["Properties"] + assert ( + every["State"] == "DISABLED" + and every["Name"] == "n" + and every["Targets"][0]["Input"] == "{}" + ) + bus = resources["FnBus"]["Properties"] + assert ( + bus["EventBusName"] == "b" + and bus["Name"] == "r" + and bus["Targets"][0]["InputPath"] == "$.x" + ) + assert resources["FnEveryPermission"]["Properties"]["Principal"] == "events.amazonaws.com" + later = resources["FnLater"] + assert later["Type"] == "AWS::Scheduler::Schedule" + assert later["Properties"]["FlexibleTimeWindow"] == {"Mode": "OFF"} + assert later["Properties"]["Target"]["Input"] == "{}" + assert resources["FnLaterRole"]["Properties"]["AssumeRolePolicyDocument"]["Statement"][0][ + "Principal" + ] == {"Service": ["scheduler.amazonaws.com"]} + managed = resources["FnRole"]["Properties"]["ManagedPolicyArns"] + assert len(managed) == 3 # basic, SQS, Kinesis + + +def test_sns_s3_and_logs_events(): + out, _, notes = expand( + { + "Bucket": {"Type": "AWS::S3::Bucket", "DependsOn": "Other"}, + "Other": {"Type": "AWS::SNS::Topic"}, + "Fn": function( + { + "Events": { + "Topic": { + "Type": "SNS", + "Properties": { + "Topic": "arn:t", + "FilterPolicy": {"a": ["b"]}, + "SqsSubscription": True, + }, + }, + "Upload": { + "Type": "S3", + "Properties": { + "Bucket": {"Ref": "Bucket"}, + "Events": ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"], + "Filter": {"S3Key": {}}, + }, + }, + "Elsewhere": { + "Type": "S3", + "Properties": {"Bucket": "external", "Events": "s3:ObjectCreated:*"}, + }, + "Logs": {"Type": "CloudWatchLogs", "Properties": {"LogGroupName": "/x"}}, + } + } + ), + } + ) + resources = out["Resources"] + assert resources["FnTopic"]["Properties"]["FilterPolicy"] == {"a": ["b"]} + bucket = resources["Bucket"] + configs = bucket["Properties"]["NotificationConfiguration"]["LambdaConfigurations"] + assert [c["Event"] for c in configs] == ["s3:ObjectCreated:*", "s3:ObjectRemoved:*"] + assert bucket["DependsOn"] == ["Other", "FnUploadPermission"] + assert resources["FnUploadPermission"]["Properties"]["SourceAccount"] == { + "Ref": "AWS::AccountId" + } + assert resources["FnLogs"]["DependsOn"] == ["FnLogsPermission"] + assert any("SqsSubscription" in n for n in notes) + assert any( + "FnElsewhere: the bucket of the S3 event is outside this template" in n for n in notes + ) + + +def test_api_events_build_the_rest_api_body(): + out, _, notes = expand( + { + "Fn": function( + { + "Events": { + "Get": { + "Type": "Api", + "Properties": {"Path": "/items/{id}", "Method": "GET"}, + }, + "Any": { + "Type": "Api", + "Properties": { + "Path": "/all", + "Method": "any", + "Auth": {"Authorizer": "X"}, + }, + }, + "Mine": { + "Type": "Api", + "Properties": { + "Path": "/mine", + "Method": "post", + "RestApiId": {"Ref": "MyApi"}, + }, + }, + "Given": { + "Type": "Api", + "Properties": { + "Path": "/g", + "Method": "get", + "RestApiId": {"Ref": "Defined"}, + }, + }, + } + } + ), + "MyApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "v1", + "Name": "mine", + "EndpointConfiguration": "REGIONAL", + "Tags": {"a": "b"}, + "MethodSettings": [{"HttpMethod": "*"}], + "Cors": "'*'", + "Description": "d", + "Odd": 1, + }, + }, + "Defined": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "prod", + "DefinitionBody": {"swagger": "2.0"}, + "EndpointConfiguration": {"Types": ["EDGE"]}, + }, + }, + "FromFile": { + "Type": "AWS::Serverless::Api", + "Properties": {"StageName": "s", "DefinitionUri": "./api.yaml"}, + }, + "FromS3": { + "Type": "AWS::Serverless::Api", + "Properties": {"StageName": "s", "DefinitionUri": "s3://b/api.yaml"}, + }, + }, + { + "Outputs": { + "Stage": {"Value": {"Ref": "MyApi.Stage"}}, + "Url": {"Value": {"Ref": "ServerlessRestApi"}}, + } + }, + ) + resources = out["Resources"] + implicit = resources["ServerlessRestApi"]["Properties"] + assert implicit["Name"] == {"Ref": "AWS::StackName"} + paths = implicit["Body"]["paths"] + assert set(paths) == {"/items/{id}", "/all"} + assert "get" in paths["/items/{id}"] and "x-amazon-apigateway-any-method" in paths["/all"] + assert set(resources["MyApi"]["Properties"]["Body"]["paths"]) == {"/mine"} + assert resources["MyApi"]["Properties"]["EndpointConfiguration"] == {"Types": ["REGIONAL"]} + assert resources["MyApi"]["Properties"]["Tags"] == [{"Key": "a", "Value": "b"}] + assert resources["MyApiv1Stage"]["Properties"]["MethodSettings"] == [{"HttpMethod": "*"}] + assert resources["Defined"]["Properties"]["Body"] == {"swagger": "2.0"} + assert resources["FromFile"]["Properties"]["Body"] == Expression( + 'yamldecode(file("${path.module}/api.yaml"))' + ) + assert resources["FromS3"]["Properties"]["BodyS3Location"] == {"Bucket": "b", "Key": "api.yaml"} + assert resources["ServerlessRestApiProdStage"]["Properties"]["StageName"] == "Prod" + get_arn = resources["FnGetPermission"]["Properties"]["SourceArn"]["Fn::Sub"][0] + assert get_arn.endswith("/*/GET/items/*") + any_arn = resources["FnAnyPermission"]["Properties"]["SourceArn"]["Fn::Sub"][0] + assert any_arn.endswith("/*/*/all") + assert out["Outputs"]["Stage"]["Value"] == {"Ref": "MyApiv1Stage"} + assert any("Auth setting of the API event was not converted" in n for n in notes) + assert any("MyApi: SAM API setting 'Cors'" in n for n in notes) + assert any("MyApi: SAM property 'Odd'" in n for n in notes) + + +def test_http_api_events(): + out, _, notes = expand( + { + "Fn": function( + { + "Events": { + "Root": {"Type": "HttpApi"}, + "Post": { + "Type": "HttpApi", + "Properties": { + "Path": "/p", + "Method": "POST", + "PayloadFormatVersion": "1.0", + "TimeoutInMillis": 5000, + "Auth": {"Authorizer": "Jwt"}, + }, + }, + "Own": { + "Type": "HttpApi", + "Properties": {"Path": "/o", "Method": "get", "ApiId": {"Ref": "Http"}}, + }, + } + } + ), + "Http": { + "Type": "AWS::Serverless::HttpApi", + "Properties": { + "StageName": "live", + "CorsConfiguration": {"AllowOrigins": ["*"]}, + "Tags": {"a": "b"}, + "Auth": {"Authorizers": {}}, + "StageVariables": {"x": "y"}, + "Description": "d", + "Odd": 1, + }, + }, + "Cors": { + "Type": "AWS::Serverless::HttpApi", + "Properties": {"CorsConfiguration": True, "DefinitionUri": "api.yaml"}, + }, + "S3": {"Type": "AWS::Serverless::HttpApi", "Properties": {"DefinitionUri": "s3://b/k"}}, + "Body": { + "Type": "AWS::Serverless::HttpApi", + "Properties": {"DefinitionBody": {"openapi": "3.0.1"}}, + }, + } + ) + resources = out["Resources"] + implicit = resources["ServerlessHttpApi"]["Properties"] + assert implicit["ProtocolType"] == "HTTP" + paths = implicit["Body"]["paths"] + assert ( + paths["$default"]["x-amazon-apigateway-any-method"]["x-amazon-apigateway-integration"][ + "payloadFormatVersion" + ] + == "2.0" + ) + post = paths["/p"]["post"]["x-amazon-apigateway-integration"] + assert post["payloadFormatVersion"] == "1.0" and post["timeoutInMillis"] == 5000 + assert resources["FnRootPermission"]["Properties"]["SourceArn"]["Fn::Sub"][0].endswith("}/*") + assert set(resources["Http"]["Properties"]["Body"]["paths"]) == {"/o"} + assert resources["Http"]["Properties"]["CorsConfiguration"] == {"AllowOrigins": ["*"]} + assert resources["HttpliveStage"]["Properties"]["StageVariables"] == {"x": "y"} + assert resources["ServerlessHttpApiApiGatewayDefaultStage"]["Properties"]["AutoDeploy"] is True + assert resources["Cors"]["Properties"]["Body"] == Expression( + 'yamldecode(file("${path.module}/api.yaml"))' + ) + assert resources["S3"]["Properties"]["BodyS3Location"] == {"Bucket": "b", "Key": "k"} + assert resources["Body"]["Properties"]["Body"] == {"openapi": "3.0.1"} + assert any("CorsConfiguration given as a single value" in n for n in notes) + assert any("Http: SAM HTTP API setting 'Auth'" in n for n in notes) + assert any("Http: SAM property 'Odd'" in n for n in notes) + assert any("FnPost: the Auth setting of the API event was not converted" in n for n in notes) + + +def test_url_alias_and_unconverted_function_settings(): + out, _, notes = expand( + { + "Fn": function( + { + "AutoPublishAlias": "live", + "FunctionUrlConfig": { + "AuthType": "NONE", + "Cors": {"AllowOrigins": ["*"]}, + "InvokeMode": "BUFFERED", + }, + "DeploymentPreference": {"Type": "Linear10PercentEvery1Minute"}, + "Events": { + "Queue": {"Type": "SQS", "Properties": {"Queue": "arn:q"}}, + "Odd": {"Type": "IoTRule"}, + }, + }, + ), + "Private": function({"FunctionUrlConfig": {}}), + }, + { + "Outputs": { + "Alias": {"Value": {"Ref": "Fn.Alias"}}, + "Version": {"Value": {"Ref": "Fn.Version"}}, + } + }, + ) + resources = out["Resources"] + assert resources["FnAliaslive"]["Properties"]["FunctionVersion"] == { + "Fn::GetAtt": ["FnVersion", "Version"] + } + assert resources["FnQueue"]["Properties"]["FunctionName"] == {"Ref": "FnAliaslive"} + url = resources["FnUrl"]["Properties"] + assert url["TargetFunctionArn"] == {"Ref": "FnAliaslive"} and url["InvokeMode"] == "BUFFERED" + assert resources["FnUrlPublicPermissions"]["Properties"]["FunctionUrlAuthType"] == "NONE" + assert resources["PrivateUrl"]["Properties"]["AuthType"] == "AWS_IAM" + assert "PrivateUrlPublicPermissions" not in resources + assert out["Outputs"] == { + "Alias": {"Value": {"Ref": "FnAliaslive"}}, + "Version": {"Value": {"Ref": "FnVersion"}}, + } + assert any("the SAM setting DeploymentPreference was not converted" in n for n in notes) + assert any("event type 'IoTRule' was not converted" in n for n in notes) + + +@pytest.mark.parametrize( + ("resources", "message"), + [ + ({"Fn": function({"Events": ["x"]})}, "'Events' of 'Fn' must be a mapping"), + ({"Fn": function({"Events": {"E": "x"}})}, "event 'E' of 'Fn' must be a mapping"), + ], +) +def test_invalid_sam(resources, message): + with pytest.raises(CfnError, match=message): + expand(resources) + with pytest.raises(CfnError, match="'Globals' must be a mapping"): + expand({"Fn": function()}, {"Globals": [1]}) + + +def test_simple_table_layer_and_other_types(): + out, hints, notes = expand( + { + "Plain": {"Type": "AWS::Serverless::SimpleTable"}, + "Custom": { + "Type": "AWS::Serverless::SimpleTable", + "Properties": { + "PrimaryKey": {"Name": "n", "Type": "Number"}, + "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}, + "TableName": "t", + "Tags": {"a": "b"}, + "Odd": 1, + }, + }, + "S3Layer": { + "Type": "AWS::Serverless::LayerVersion", + "Properties": { + "ContentUri": {"Bucket": "b", "Key": "k", "Version": "1"}, + "LayerName": "l", + }, + }, + "UriLayer": { + "Type": "AWS::Serverless::LayerVersion", + "Properties": {"ContentUri": "s3://b/k", "RetentionPolicy": "Retain", "Odd": 1}, + }, + "LocalLayer": { + "Type": "AWS::Serverless::LayerVersion", + "Properties": {"ContentUri": "layer/"}, + }, + "App": {"Type": "AWS::Serverless::Application"}, + } + ) + resources = out["Resources"] + assert resources["Plain"]["Properties"]["KeySchema"] == [ + {"AttributeName": "id", "KeyType": "HASH"} + ] + assert resources["Plain"]["Properties"]["BillingMode"] == "PAY_PER_REQUEST" + custom = resources["Custom"]["Properties"] + assert custom["AttributeDefinitions"] == [{"AttributeName": "n", "AttributeType": "N"}] + assert "BillingMode" not in custom and custom["TableName"] == "t" + assert resources["S3Layer"]["Properties"]["Content"] == { + "S3Bucket": "b", + "S3Key": "k", + "S3ObjectVersion": "1", + } + assert resources["UriLayer"]["Properties"]["Content"] == {"S3Bucket": "b", "S3Key": "k"} + assert resources["UriLayer"]["DeletionPolicy"] == "Retain" + assert hints["LocalLayer"] == {"code_path": "layer"} + assert "App" not in resources + assert any("App (AWS::Serverless::Application) was not converted" in n for n in notes) + assert any("Custom: SAM property 'Odd'" in n for n in notes) + assert any("UriLayer: SAM property 'Odd'" in n for n in notes) + + +def test_state_machines(): + out, _, notes = expand( + { + "Flow": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "Definition": { + "States": { + "A": { + "Resource": "${Fn}", + "Static": "${Plain}", + "Other": "${Unused}", + "List": ["${Plain}"], + } + } + }, + "DefinitionSubstitutions": {"Fn": {"Fn::GetAtt": ["X", "Arn"]}, "Plain": "p"}, + "Name": "flow", + "Type": "EXPRESS", + "Logging": {"Level": "ALL"}, + "Tracing": {"Enabled": True}, + "Tags": {"a": "b"}, + "PermissionsBoundary": "arn:b", + "Policies": ["AWSXrayWriteOnlyAccess"], + "Events": { + "Every": { + "Type": "Schedule", + "Properties": {"Schedule": "rate(1 day)", "Input": "{}"}, + }, + "Bus": { + "Type": "EventBridgeRule", + "Properties": {"Pattern": {"source": ["x"]}}, + }, + "Later": { + "Type": "ScheduleV2", + "Properties": {"ScheduleExpression": "rate(1 day)"}, + }, + "Http": {"Type": "Api"}, + }, + "Odd": 1, + }, + }, + "FromFile": { + "Type": "AWS::Serverless::StateMachine", + "Properties": { + "DefinitionUri": "flow.asl.json", + "DefinitionSubstitutions": {"A": "b"}, + "Role": "arn:role", + }, + }, + "FromS3": { + "Type": "AWS::Serverless::StateMachine", + "Properties": {"DefinitionUri": "s3://b/k", "DefinitionSubstitutions": {"A": "b"}}, + }, + } + ) + resources = out["Resources"] + flow = resources["Flow"]["Properties"] + state = flow["Definition"]["States"]["A"] + assert state["Resource"] == {"Fn::Sub": ["${Fn}", {"Fn": {"Fn::GetAtt": ["X", "Arn"]}}]} + assert state["Static"] == "p" and state["Other"] == "${Unused}" and state["List"] == ["p"] + assert flow["StateMachineName"] == "flow" and flow["StateMachineType"] == "EXPRESS" + assert flow["RoleArn"] == {"Fn::GetAtt": ["FlowRole", "Arn"]} + assert resources["FlowRole"]["Properties"]["PermissionsBoundary"] == "arn:b" + assert resources["FlowEvery"]["Properties"]["Targets"][0]["Input"] == "{}" + assert ( + resources["FlowEveryRole"]["Properties"]["Policies"][0]["PolicyName"] + == "FlowEveryStartExecution" + ) + assert resources["FlowLater"]["Type"] == "AWS::Scheduler::Schedule" + assert resources["FromFile"]["Properties"]["Definition"] == Expression( + 'yamldecode(file("${path.module}/flow.asl.json"))' + ) + assert resources["FromFile"]["Properties"]["RoleArn"] == "arn:role" + assert "FromFileRole" not in resources + assert resources["FromS3"]["Properties"]["DefinitionS3Location"] == {"Bucket": "b", "Key": "k"} + assert resources["FromS3"]["Properties"]["DefinitionSubstitutions"] == {"A": "b"} + assert any("FlowHttp: SAM state machine event type 'Api'" in n for n in notes) + assert any("FromFile: DefinitionSubstitutions for a definition file" in n for n in notes) + assert any("Flow: SAM property 'Odd'" in n for n in notes) + + +def test_connectors(): + out, _, notes = expand( + { + "Fn": with_attributes( + function(), + { + "Connectors": { + "ToTable": { + "Properties": { + "Destination": {"Id": "Table"}, + "Permissions": ["Read", "Write"], + } + }, + "ToMany": { + "Properties": { + "Destination": [ + {"Id": "Bucket"}, + {"Id": "Queue"}, + {"Id": "Topic"}, + {"Id": "Flow"}, + {"Id": "Missing"}, + ], + "Permissions": ["Write"], + } + }, + }, + }, + ), + "Table": {"Type": "AWS::Serverless::SimpleTable"}, + "Bucket": {"Type": "AWS::S3::Bucket"}, + "Queue": {"Type": "AWS::SQS::Queue"}, + "Topic": {"Type": "AWS::SNS::Topic"}, + "Flow": {"Type": "AWS::Serverless::StateMachine", "Properties": {"Definition": {}}}, + "Api": {"Type": "AWS::Serverless::Api", "Properties": {"StageName": "s"}}, + "Rule": {"Type": "AWS::Events::Rule"}, + "ApiToFn": { + "Type": "AWS::Serverless::Connector", + "Properties": { + "Source": {"Id": "Api"}, + "Destination": {"Id": "Fn"}, + "Permissions": ["Write"], + }, + }, + "TopicToFn": { + "Type": "AWS::Serverless::Connector", + "Properties": { + "Source": {"Id": "Topic"}, + "Destination": {"Id": "Fn"}, + "Permissions": ["Write"], + }, + }, + "RuleToFn": { + "Type": "AWS::Serverless::Connector", + "Properties": { + "Source": {"Id": "Rule"}, + "Destination": {"Id": "Fn"}, + "Permissions": ["Write"], + }, + }, + "QueueToTopic": { + "Type": "AWS::Serverless::Connector", + "Properties": { + "Source": {"Id": "Queue"}, + "Destination": {"Id": "Topic"}, + "Permissions": ["Write"], + }, + }, + "FnToNothing": { + "Type": "AWS::Serverless::Connector", + "Properties": { + "Source": "Fn", + "Destination": {"Ref": "Topic"}, + "Permissions": ["Read"], + }, + }, + } + ) + resources = out["Resources"] + policies = { + p["PolicyName"]: p["PolicyDocument"]["Statement"][0] + for p in resources["FnRole"]["Properties"]["Policies"] + } + table = policies["FnToTablePolicy"] + assert "dynamodb:GetItem" in table["Action"] and "dynamodb:PutItem" in table["Action"] + assert table["Resource"][1] == { + "Fn::Sub": ["${arn}/index/*", {"arn": {"Fn::GetAtt": ["Table", "Arn"]}}] + } + assert "s3:PutObject" in policies["FnToManyPolicyDestination0"]["Action"] + assert policies["FnToManyPolicyDestination2"]["Resource"] == [{"Ref": "Topic"}] + assert policies["FnToManyPolicyDestination3"]["Resource"] == [{"Ref": "Flow"}] + assert ( + resources["ApiToFnWriteLambdaPermission"]["Properties"]["Principal"] + == "apigateway.amazonaws.com" + ) + assert resources["TopicToFnWriteLambdaPermission"]["Properties"]["SourceArn"] == { + "Ref": "Topic" + } + assert resources["RuleToFnWriteLambdaPermission"]["Properties"]["SourceArn"] == { + "Fn::GetAtt": ["Rule", "Arn"] + } + assert any("FnToMany: a connector end is outside this template" in n for n in notes) + assert any( + "QueueToTopic: connector from AWS::SQS::Queue to AWS::SNS::Topic" in n for n in notes + ) + assert any( + "FnToNothing: connector from AWS::Lambda::Function to AWS::SNS::Topic" in n for n in notes + ) + + +def test_other_transforms_are_kept(): + out, _, _ = expand({"B": {"Type": "AWS::S3::Bucket"}}) + assert "Transform" not in out + notes: list[str] = [] + out, _ = expand_sam( + { + "Transform": [TRANSFORM, "AWS::LanguageExtensions"], + "Resources": {"B": {"Type": "AWS::S3::Bucket"}}, + }, + notes, + ) + assert out["Transform"] == ["AWS::LanguageExtensions"] + + +def test_resource_attributes_computed_tags_and_odd_definition_uri(): + out, _, _ = expand( + { + "Fn": with_attributes( + function({"Tags": {"Fn::If": ["C", {"a": "b"}, {"Ref": "AWS::NoValue"}]}}), + { + "Condition": "C", + "DeletionPolicy": "Retain", + }, + ), + "Api": { + "Type": "AWS::Serverless::Api", + "Properties": {"StageName": "s", "DefinitionUri": {"Bucket": "b", "Key": "k"}}, + }, + }, + {"Conditions": {"C": {"Fn::Equals": ["a", "a"]}}}, + ) + resources = out["Resources"] + assert resources["Fn"]["Properties"]["Tags"] == { + "Fn::If": ["C", {"a": "b"}, {"Ref": "AWS::NoValue"}] + } + assert ( + resources["FnRole"]["Condition"] == "C" + and resources["FnRole"]["DeletionPolicy"] == "Retain" + ) + assert resources["Api"]["Properties"]["BodyS3Location"] == {"Bucket": "b", "Key": "k"} + + +def test_vpc_function_and_aliases_in_sub(): + out, _, _ = expand( + {"Fn": function({"VpcConfig": {"SubnetIds": ["s"]}, "AutoPublishAlias": "live"})}, + { + "Outputs": { + "Text": {"Value": {"Fn::Sub": "${Fn.Alias} ${Fn.Arn}"}}, + "List": {"Value": {"Fn::Sub": ["${Fn.Version}-${x}", {"x": {"Ref": "Fn.Alias"}}]}}, + } + }, + ) + managed = out["Resources"]["FnRole"]["Properties"]["ManagedPolicyArns"] + assert { + "Fn::Sub": "arn:${AWS::Partition}:iam::aws:policy/service-role/" + "AWSLambdaVPCAccessExecutionRole" + } in managed + assert out["Outputs"]["Text"]["Value"] == {"Fn::Sub": "${FnAliaslive} ${Fn.Arn}"} + assert out["Outputs"]["List"]["Value"] == { + "Fn::Sub": ["${FnVersion}-${x}", {"x": {"Ref": "FnAliaslive"}}] + } diff --git a/services/converter-api/tests/test_cfn_storage.py b/services/converter-api/tests/test_cfn_storage.py new file mode 100644 index 0000000..f576492 --- /dev/null +++ b/services/converter-api/tests/test_cfn_storage.py @@ -0,0 +1,631 @@ +"""S3, DynamoDB and ECR mappings (converters/cfn/resources/storage.py).""" + +from __future__ import annotations + +import re +from pathlib import Path + +import yaml + +from converters.cfn.convert import Converter +from converters.cfn.parse import load_template +from converters.cfn.pipeline import convert_template + +FIXTURE = Path(__file__).parent / "fixtures" / "cfn" / "storage.yaml" + + +def squeeze(text: str) -> str: + return re.sub(r" +", " ", text) + + +def convert(resources: dict, extra: dict | None = None) -> tuple[str, list[str]]: + template = {"Resources": resources} + template.update(extra or {}) + result = convert_template(yaml.safe_dump(template), stack_name="demo") + main = next(f["content"] for f in result["files"] if f["path"] == "main.tf") + return squeeze(main), result["notes"] + + +def test_fixture_converts_everything(): + result = convert_template(FIXTURE.read_text(), stack_name="demo") + assert result["summary"]["unsupported"] == 0 + assert not [n for n in result["notes"] if "was not converted" in n] + files = {f["path"]: squeeze(f["content"]) for f in result["files"]} + main = files["main.tf"] + assert "kms_key_arn = data.aws_kms_key.events_sse_key.arn" in main + assert "stream_enabled = local.with_website" in main + assert 'dynamic "attribute"' in main and 'dynamic "transition"' in main + assert "eventbridge = local.with_website ? true : false" in main + for kind in ( + "aws_s3_bucket_versioning", + "aws_s3_bucket_server_side_encryption_configuration", + "aws_s3_bucket_public_access_block", + "aws_s3_bucket_ownership_controls", + "aws_s3_bucket_acl", + "aws_s3_bucket_lifecycle_configuration", + "aws_s3_bucket_cors_configuration", + "aws_s3_bucket_website_configuration", + "aws_s3_bucket_logging", + "aws_s3_bucket_accelerate_configuration", + "aws_s3_bucket_object_lock_configuration", + "aws_s3_bucket_notification", + "aws_s3_bucket_policy", + "aws_dynamodb_table", + "aws_ecr_repository", + "aws_ecr_lifecycle_policy", + "aws_ecr_repository_policy", + ): + assert f'resource "{kind}"' in main, kind + assert 'acl = "log-delivery-write"' in main + assert "depends_on = [aws_s3_bucket_ownership_controls.logs_ownership]" in main + assert "target_bucket = aws_s3_bucket.logs.id" in main + assert 'target_prefix = "assets/"' in main + assert 'target_bucket = aws_s3_bucket.redirect.id\n target_prefix = ""' in main + assert 'filter_prefix = "uploads/"' in main and 'filter_suffix = ".jpg"' in main + assert "max_age_seconds = 3600" in main + assert 'replace_key_prefix_with = "documents/"' in main + assert 'range_key = "sk"' in main and "read_capacity = 5" in main + assert 'non_key_attributes = ["total"]' in main + assert 'projection_type = "ALL"' in main # an empty Projection means ALL + assert "stream_enabled = true" in main + assert "max_read_request_units = 100" in main + assert 'name = "shop/images"' in main and "force_delete = true" in main + assert 'name = "${var.stack_name}-cache"' in main + outputs = files["outputs.tf"] + website = "aws_s3_bucket_website_configuration.site_website[0].website_endpoint" + assert f'value = local.with_website ? "http://${{{website}}}" : null' in outputs + assert "value = aws_s3_bucket.assets.bucket_regional_domain_name" in outputs + assert "value = aws_ecr_repository.images.repository_url" in outputs + + +def test_access_control_without_ownership_controls_is_noted(): + main, notes = convert( + {"B": {"Type": "AWS::S3::Bucket", "Properties": {"AccessControl": "Private"}}} + ) + assert 'acl = "private"' in main and "depends_on" not in main + assert any("S3 disables ACLs by default" in n for n in notes) + + +def test_computed_access_control(): + main, _ = convert( + {"B": {"Type": "AWS::S3::Bucket", "Properties": {"AccessControl": {"Fn::Sub": "x"}}}} + ) + assert 'acl = "x"' in main + + +def test_lifecycle_without_id_or_filter(): + main, _ = convert( + { + "B": { + "Type": "AWS::S3::Bucket", + "Properties": { + "LifecycleConfiguration": { + "Rules": [{"Status": "Enabled", "ExpirationInDays": 1}] + } + }, + } + } + ) + assert 'id = "rule-1"' in main and "filter {}" in main + + +def test_lifecycle_tag_and_size_filters_combine_into_and(): + main, _ = convert( + { + "B": { + "Type": "AWS::S3::Bucket", + "Properties": { + "LifecycleConfiguration": { + "Rules": [ + { + "Status": "Enabled", + "ObjectSizeLessThan": 5, + "TagFilters": [{"Key": "a", "Value": "b"}], + "ExpirationInDays": 1, + }, + { + "Status": "Enabled", + "ObjectSizeGreaterThan": 5, + "ExpirationInDays": 1, + }, + ] + } + }, + } + } + ) + assert 'and {\n object_size_less_than = 5\n tags = {\n a = "b"\n }\n }' in main + assert "filter {\n object_size_greater_than = 5\n }" in main + + +def test_conditional_bucket_sub_resources_share_the_condition(): + main, _ = convert( + { + "B": { + "Type": "AWS::S3::Bucket", + "Condition": "On", + "Properties": {"VersioningConfiguration": {"Status": "Enabled"}}, + } + }, + {"Conditions": {"On": {"Fn::Equals": ["a", "a"]}}}, + ) + assert main.count("count = local.on ? 1 : 0") == 2 + assert "bucket = aws_s3_bucket.b[0].id" in main + + +def test_cdk_auto_delete_hint_sets_force_destroy(): + template = load_template(yaml.safe_dump({"Resources": {"B": {"Type": "AWS::S3::Bucket"}}})) + result = Converter(template, hints={"B": {"force_destroy": True}}).run("single") + assert "force_destroy = true" in result["files"][0]["content"] + + +def test_dynamic_versioning_and_notification_with_odd_filters(): + main, _ = convert( + { + "B": { + "Type": "AWS::S3::Bucket", + "Properties": { + "NotificationConfiguration": { + "QueueConfigurations": [ + {"Event": "s3:ObjectCreated:*", "Queue": "arn:q", "Filter": "odd"}, + { + "Event": "s3:ObjectCreated:*", + "Queue": "arn:q2", + "Filter": {"S3Key": {"Rules": [{"Name": "other", "Value": "x"}]}}, + }, + ], + "EventBridgeConfiguration": "yes", + } + }, + } + } + ) + assert 'queue_arn = "arn:q"' in main and "filter_" not in main + assert "eventbridge" not in main + + +def test_dynamodb_table_with_only_a_hash_key_and_no_stream(): + main, notes = convert( + { + "T": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "TableName": "t", + "KeySchema": "computed", + "LocalSecondaryIndexes": [ + {"IndexName": "l", "KeySchema": [], "Projection": "x"} + ], + }, + } + } + ) + assert 'name = "t"' in main and "hash_key" not in main + assert 'local_secondary_index {\n name = "l"\n # Projection was not converted: "x"\n }' in main + assert '# KeySchema was not converted: "computed"' in main + assert not any("TableName" in n for n in notes) + + +def test_ecr_lifecycle_policy_without_text_is_ignored(): + main, _ = convert( + { + "R": { + "Type": "AWS::ECR::Repository", + "Properties": {"RepositoryName": "r", "LifecyclePolicy": {}}, + } + } + ) + assert "aws_ecr_lifecycle_policy" not in main + + +def test_lifecycle_dates_single_noncurrent_transition_and_string_booleans(): + main, _ = convert( + { + "B": { + "Type": "AWS::S3::Bucket", + "Properties": { + "LifecycleConfiguration": { + "Rules": [ + { + "Status": "Enabled", + "ExpiredObjectDeleteMarker": "true", + "Transition": { + "StorageClass": "GLACIER", + "TransitionDate": "2030-01-01T00:00:00Z", + }, + "NoncurrentVersionTransition": { + "StorageClass": "GLACIER", + "TransitionInDays": 5, + }, + } + ] + } + }, + } + } + ) + assert "expired_object_delete_marker = true" in main + assert 'date = "2030-01-01T00:00:00Z"' in main + assert "noncurrent_version_transition {\n noncurrent_days = 5" in main + + +# --- regression tests for the review findings ------------------------------------------- + +NO = {"Ref": "AWS::NoValue"} +CONDITION = { + "Parameters": {"Env": {"Type": "String"}, "List": {"Type": "String"}}, + "Conditions": {"On": {"Fn::Equals": [{"Ref": "Env"}, "on"]}}, +} +EVIL = 'x" ${file("/etc/passwd")} y' +TABLE = { + "TableName": "t", + "BillingMode": "PAY_PER_REQUEST", + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], +} + + +def optional(value): + return {"Fn::If": ["On", value, NO]} + + +def table(properties: dict) -> dict: + """A table with the TABLE properties plus `properties`.""" + merged = dict(TABLE) + merged.update(properties) + return {"Type": "AWS::DynamoDB::Table", "Properties": merged} + + +def bucket_rule(rule: dict) -> dict: + """A bucket with one enabled lifecycle rule made of `rule`.""" + merged = {"Status": "Enabled"} + merged.update(rule) + return { + "Type": "AWS::S3::Bucket", + "Properties": {"LifecycleConfiguration": {"Rules": [merged]}}, + } + + +def assert_no_injection(main: str) -> None: + code = "\n".join(line for line in main.splitlines() if not line.lstrip().startswith("#")) + assert 'file("' not in code + assert not re.search(r"(? main.tf <<'EOF' + terraform { + required_providers { + awscc = { source = "hashicorp/awscc" } + } + } + EOF + terraform init && terraform providers schema -json > schema.json + curl -sSfLO https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip + cd /services/converter-api + python -m tools.build_awscc_index /tmp/awscc/schema.json /tmp/awscc/CloudformationSchema.zip + +Run it as a module from services/converter-api, so `converters` is importable. +""" + +from __future__ import annotations + +import json +import sys +import zipfile +from pathlib import Path +from typing import Any + +from converters.cfn.naming import snake + +OUTPUT = Path(__file__).resolve().parents[1] / "converters" / "cfn" / "awscc_index.json" +_PROVIDER = "registry.terraform.io/hashicorp/awscc" +_MAX_DEPTH = 12 + + +def _resolve(spec: Any, definitions: dict[str, Any]) -> dict[str, Any]: + """`spec` with its `$ref` chain (into #/definitions) followed, or {} when it leads out.""" + for _ in range(20): + if not (isinstance(spec, dict) and "$ref" in spec): + break + ref = spec["$ref"] + if not ref.startswith("#/definitions/"): + return {} + spec = definitions.get(ref.split("/")[-1], {}) + return spec if isinstance(spec, dict) else {} + + +def _is_object(spec: dict[str, Any]) -> bool: + """Whether a JSON schema describes an object.""" + kind = spec.get("type") + return kind == "object" or (isinstance(kind, list) and "object" in kind) + + +def _walk( + props: dict[str, Any], + definitions: dict[str, Any], + attributes: dict[str, Any], + path: list[str], + entry: dict[str, Any], + depth: int = 0, +) -> None: + """Record into `entry` the maps, JSON documents, renamed and missing properties of + `props` (CloudFormation schema) against `attributes` (awscc schema), at `path`.""" + if depth > _MAX_DEPTH: + return + flat = {name.replace("_", ""): name for name in attributes} + for prop, raw in props.items(): + full = ".".join(path + [prop]) + name = snake(prop) + if name not in attributes: + alternative = flat.get(prop.lower()) + if alternative is None: + entry["x"].append(full) + continue + entry["r"][full] = alternative + name = alternative + attribute = attributes[name] + spec = _resolve(raw, definitions) + kind = attribute.get("type") + if isinstance(kind, list) and kind[0] == "map": + entry["m"].append(full) + continue + if kind == "string" and ( + _is_object(spec) or "oneOf" in spec or "anyOf" in spec or spec.get("type") == "array" + ): + entry["j"].append(full) + continue + if isinstance(kind, list) and kind[0] in ("list", "set") and kind[1] == "string": + if _is_object(_resolve(spec.get("items", {}), definitions)): + entry["j"].append(full) + continue + nested = attribute.get("nested_type") + if not nested: + continue + if nested["nesting_mode"] == "map": + entry["m"].append(full) + continue + inner = ( + _resolve(spec.get("items", {}), definitions) if spec.get("type") == "array" else spec + ) + if "properties" in inner: + _walk( + inner["properties"], + definitions, + nested.get("attributes", {}), + path + [prop], + entry, + depth + 1, + ) + + +def build(provider_schema: Path, cloudformation_zip: Path) -> dict[str, Any]: + """The index for every CloudFormation type in the zip that awscc has.""" + resources = json.loads(provider_schema.read_text())["provider_schemas"][_PROVIDER][ + "resource_schemas" + ] + flat_types = {name.replace("_", ""): name for name in resources} + index: dict[str, Any] = {} + with zipfile.ZipFile(cloudformation_zip) as archive: + for member in sorted(archive.namelist()): + if not member.endswith(".json"): + continue + schema = json.loads(archive.read(member)) + cfn_type = schema["typeName"] + _, service, kind = cfn_type.split("::") + name = f"awscc_{service.lower()}_{snake(kind)}" + entry: dict[str, Any] = {"m": [], "j": [], "r": {}, "x": []} + if name not in resources: + alternative = flat_types.get(name.replace("_", "")) + if alternative is None: + continue + name = entry["n"] = alternative + _walk( + schema.get("properties", {}), + schema.get("definitions", {}), + resources[name]["block"]["attributes"], + [], + entry, + ) + settable = sorted( + attribute + for attribute, spec in resources[name]["block"]["attributes"].items() + if spec.get("optional") or spec.get("required") + ) + entry["a"] = " ".join(settable) + index[cfn_type] = { + key: sorted(set(value)) if isinstance(value, list) else value + for key, value in entry.items() + if value + } + return index + + +def main(arguments: list[str]) -> int: + """Build the index from the two files in `arguments` and write it to OUTPUT.""" + if len(arguments) != 2: + print(__doc__, file=sys.stderr) + return 2 + result = build(Path(arguments[0]), Path(arguments[1])) + OUTPUT.write_text(json.dumps(result, indent=1, sort_keys=True) + "\n", encoding="utf-8") + print(f"{len(result)} resource types written to {OUTPUT}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/services/converter-api/tools/convert_fixtures.py b/services/converter-api/tools/convert_fixtures.py new file mode 100644 index 0000000..2c18d47 --- /dev/null +++ b/services/converter-api/tools/convert_fixtures.py @@ -0,0 +1,76 @@ +"""Convert the CloudFormation fixtures in tests/fixtures/cfn into Terraform directories, +which scripts/validate-terraform.sh then checks with terraform fmt, init and validate. + +Each fixture is converted twice: with the aws provider (separate files and import blocks) +and with the awscc provider only (one file, stack name demo). Local paths the configuration +reads (Lambda code, API definitions) are created as dummy files and folders, so validate +finds them. Writes OUTDIR//aws and OUTDIR//awscc. + +Run from services/converter-api: + + python -m tools.convert_fixtures OUTDIR # every fixture + python -m tools.convert_fixtures OUTDIR network.yaml # some of them +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path +from typing import Any + +from converters.cfn.pipeline import convert_template + +FIXTURES = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "cfn" +# Local paths the configuration reads (Lambda code, API definitions): validate wants them. +LOCAL_PATH = re.compile(r'"\$\{path\.module\}/([^"$]+)"') +# Paths with these suffixes are files; any other path is a code folder. +FILE_SUFFIXES = (".zip", ".jar", ".yaml", ".yml", ".json") +# archive_file writes its zip under build/, so that folder is left for Terraform. +OUTPUT_PREFIX = "build/" +HANDLER = "def handler(event, context):\n pass\n" + + +def convert(fixture: Path, provider: str) -> dict[str, Any]: + """One conversion of one fixture: aws with separate files and import blocks, or awscc + in one file.""" + text = fixture.read_text(encoding="utf-8") + if provider == "aws": + return convert_template( + text, provider="aws", layout="files", stack_name="demo", include_imports=True + ) + return convert_template(text, provider="awscc", layout="single", stack_name="demo") + + +def write(result: dict[str, Any], directory: Path) -> None: + """Write the Terraform files of `result`, and dummies for the local paths they read.""" + directory.mkdir(parents=True, exist_ok=True) + for file in result["files"]: + (directory / file["path"]).write_text(file["content"], encoding="utf-8") + text = "\n".join(file["content"] for file in result["files"]) + for path in sorted(set(LOCAL_PATH.findall(text))): + target = directory / path + if target.suffix in FILE_SUFFIXES: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("{}\n", encoding="utf-8") + elif not path.startswith(OUTPUT_PREFIX): + target.mkdir(parents=True, exist_ok=True) + (target / "index.py").write_text(HANDLER, encoding="utf-8") + + +def main(arguments: list[str]) -> int: + """Convert the fixtures named in `arguments[1:]` (all when none) into `arguments[0]`.""" + if not arguments: + print(__doc__, file=sys.stderr) + return 2 + outdir = Path(arguments[0]) + names = arguments[1:] + fixtures = [FIXTURES / name for name in names] if names else sorted(FIXTURES.iterdir()) + for fixture in fixtures: + for provider in ("aws", "awscc"): + write(convert(fixture, provider), outdir / fixture.name / provider) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/services/converter-api/tools/validate_report.py b/services/converter-api/tools/validate_report.py new file mode 100644 index 0000000..a924fe7 --- /dev/null +++ b/services/converter-api/tools/validate_report.py @@ -0,0 +1,44 @@ +"""Read the output of `terraform validate -json` on stdin and print each diagnostic. + +Exits 1 when there is any diagnostic (warnings count as failures) or the output is not +JSON, so scripts/validate-terraform.sh can fail on it. Run from services/converter-api: + + terraform validate -json -no-color | python -m tools.validate_report +""" + +from __future__ import annotations + +import json +import sys +from typing import Any + + +def describe(diagnostic: dict[str, Any]) -> str: + """One diagnostic as severity, summary, file:line and detail.""" + where = diagnostic.get("range", {}) + position = f"{where.get('filename', '?')}:{where.get('start', {}).get('line', '?')}" + return ( + f"{diagnostic['severity']}: {diagnostic['summary']} ({position})\n" + f" {diagnostic.get('detail', '')}" + ) + + +def problems(text: str) -> list[str]: + """Every problem in the validate output `text` (empty when the configuration is valid).""" + try: + report = json.loads(text) + except ValueError: + return [f"terraform validate:\n{text}"] + return [describe(diagnostic) for diagnostic in report.get("diagnostics", [])] + + +def main() -> int: + """Print the problems in the report on stdin. Returns 1 when there are any.""" + found = problems(sys.stdin.read()) + for problem in found: + print(problem) + return 1 if found else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/services/web/.dockerignore b/services/web/.dockerignore index 1b51bb9..848d397 100644 --- a/services/web/.dockerignore +++ b/services/web/.dockerignore @@ -1,6 +1,6 @@ tests/ -__pycache__/ -*.pyc +**/__pycache__/ +**/*.pyc .pytest_cache/ .ruff_cache/ .coverage diff --git a/services/web/Dockerfile b/services/web/Dockerfile index 2ebc78b..73b59cc 100644 --- a/services/web/Dockerfile +++ b/services/web/Dockerfile @@ -61,7 +61,8 @@ RUN groupadd --system --gid 10001 app \ COPY --from=builder /opt/venv /opt/venv WORKDIR /app -COPY --chown=app:app main.py api_client.py ./ +COPY --chown=app:app *.py ./ +COPY --chown=app:app routes/ routes/ COPY --chown=app:app templates/ templates/ COPY --chown=app:app static/ static/ COPY --from=css --chown=app:app /out/app.css static/app.css diff --git a/services/web/api_client.py b/services/web/api_client.py index 7820054..4fb5429 100644 --- a/services/web/api_client.py +++ b/services/web/api_client.py @@ -25,6 +25,7 @@ class GoogleIdTokens: """Fetches and caches ID tokens so Cloud Run lets this service call a private service.""" def __init__(self, audience: str, client: httpx.AsyncClient) -> None: + """Fetch tokens for `audience` with `client`.""" self._audience = audience self._client = client self._token: str | None = None @@ -32,6 +33,7 @@ def __init__(self, audience: str, client: httpx.AsyncClient) -> None: self._lock = asyncio.Lock() async def get(self) -> str: + """A valid ID token, fetched from the metadata server when the cached one expired.""" async with self._lock: if self._token is None or time.monotonic() >= self._expires_at: response = await self._client.get( @@ -46,6 +48,8 @@ async def get(self) -> str: class ApiClient: + """An HTTP client for converter-api, with Google ID tokens when auth is google.""" + def __init__( self, base_url: str, @@ -53,6 +57,7 @@ def __init__( transport: httpx.AsyncBaseTransport | None = None, timeout: float = 15.0, ) -> None: + """A client for converter-api at `base_url`. Raises ValueError for an unknown auth.""" if auth not in AUTH_MODES: raise ValueError(f"CONVERTER_API_AUTH must be one of {', '.join(AUTH_MODES)}") self._client = httpx.AsyncClient( @@ -63,8 +68,8 @@ def __init__( ) async def post(self, path: str, payload: dict[str, Any]) -> tuple[int, dict[str, Any]]: - """POST JSON and return (status, body). Raises ApiUnavailableError for anything that - isn't an answer from converter-api itself: network errors, auth failures, 5xx.""" + """POST JSON and return (status, body). Raises ApiUnavailableError for anything other + than an answer from converter-api itself: network errors, auth failures and 5xx.""" try: headers = {} if self._tokens is not None: @@ -83,4 +88,5 @@ async def post(self, path: str, payload: dict[str, Any]) -> tuple[int, dict[str, return response.status_code, body async def aclose(self) -> None: + """Close the connections.""" await self._client.aclose() diff --git a/services/web/archives.py b/services/web/archives.py new file mode 100644 index 0000000..e9a8384 --- /dev/null +++ b/services/web/archives.py @@ -0,0 +1,38 @@ +"""Zip downloads of converted files.""" + +from __future__ import annotations + +import io +import zipfile +from typing import Any + +from fastapi.responses import StreamingResponse + +from messages import NOTES_INTRO, NOTES_NONE, NOTES_TITLE +from settings import NOTES_FILE_NAME, SOURCE_LABELS + + +def zip_download(files: list[dict[str, Any]], name: str) -> StreamingResponse: + """A response that downloads `files` (each with a path and content) as a zip named `name`.""" + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + for file in files: + archive.writestr(file["path"], file["content"]) + buffer.seek(0) + return StreamingResponse( + buffer, + media_type="application/zip", + headers={"Content-Disposition": f'attachment; filename="{name}"'}, + ) + + +def notes_file(notes: list[str], source: str) -> dict[str, str]: + """The conversion notes as a file for the zip, so they travel with the code.""" + return {"path": NOTES_FILE_NAME, "content": notes_markdown(notes, source)} + + +def notes_markdown(notes: list[str], source: str) -> str: + """The conversion notes as Markdown.""" + lines = [NOTES_TITLE, "", NOTES_INTRO.format(source=SOURCE_LABELS.get(source, source)), ""] + lines += [f"- {note}" for note in notes] or [NOTES_NONE] + return "\n".join(lines) + "\n" diff --git a/services/web/conversions.py b/services/web/conversions.py new file mode 100644 index 0000000..1fc9ec6 --- /dev/null +++ b/services/web/conversions.py @@ -0,0 +1,132 @@ +"""Sends checked input to converter-api and turns each answer into what the page shows.""" + +from __future__ import annotations + +from typing import Any + +from fastapi import Request, UploadFile + +from api_client import ApiClient, ApiUnavailableError +from errors import InputError +from inputs import check_cfn, check_compose, read_input +from log_config import logger +from messages import CONVERTER_FAILED, EMPTY_TEMPLATE, UNAVAILABLE, VALIDATOR_FAILED +from models import CfnForm, ComposeForm, Outcome +from settings import ( + CFN_API_PATH, + COMPOSE_API_PATH, + DEFAULT_SOURCE, + MAX_TEMPLATE_CHARS, + VALIDATE_API_PATH, +) + + +class ConverterService: + """The three tools of the site, each one call to converter-api.""" + + def __init__(self, api: ApiClient) -> None: + """Use `api` to reach converter-api.""" + self.api = api + + async def compose(self, form: ComposeForm, upload: UploadFile | None) -> Outcome: + """Convert a Compose file to Kubernetes manifests or a Helm chart.""" + context = form.context() + try: + context["compose_yaml"] = await read_input(form.compose_yaml, upload) + check_compose(form) + except InputError as exc: + return Outcome(context | {"error": str(exc)}, 400) + payload = { + "compose_yaml": context["compose_yaml"], + "namespace": form.namespace, + "include_service": form.include_service, + "output": form.output, + } + answer = await self.post(COMPOSE_API_PATH, payload) + if answer is None: + return Outcome(context | {"error": UNAVAILABLE}, 502) + status, body = answer + if not self.converted(status, body): + return self.rejected(context, body) + return Outcome(context | {"files": body["files"], "notes": body.get("notes", [])}) + + async def cfn(self, form: CfnForm, upload: UploadFile | None) -> Outcome: + """Convert a CloudFormation, AWS SAM or synthesized AWS CDK template to Terraform.""" + context = form.context() + try: + context["template"] = await read_input( + form.template, upload, MAX_TEMPLATE_CHARS, EMPTY_TEMPLATE + ) + check_cfn(form) + except InputError as exc: + return Outcome(context | {"error": str(exc)}, 400) + payload: dict[str, Any] = { + "template": context["template"], + "provider": form.provider, + "layout": form.layout, + "include_imports": form.include_imports, + } + if form.stack_name: + payload["stack_name"] = form.stack_name + answer = await self.post(CFN_API_PATH, payload) + if answer is None: + return Outcome(context | {"error": UNAVAILABLE}, 502) + status, body = answer + if not self.converted(status, body): + return self.rejected(context, body) + return Outcome( + context + | { + "files": body["files"], + "notes": body.get("notes", []), + "resources": body.get("resources", []), + "summary": body.get("summary", {}), + "source": body.get("source", DEFAULT_SOURCE), + } + ) + + async def validate_yaml(self, text: str, upload: UploadFile | None) -> Outcome: + """Check that the text is valid YAML.""" + context: dict[str, Any] = {"yaml_text": text} + try: + context["yaml_text"] = await read_input(text, upload) + except InputError as exc: + return Outcome(context | {"error": str(exc)}, 400) + answer = await self.post(VALIDATE_API_PATH, {"yaml": context["yaml_text"]}) + if answer is None: + return Outcome(context | {"error": UNAVAILABLE}, 502) + status, body = answer + if status != 200 or "valid" not in body: + return Outcome(context | {"error": VALIDATOR_FAILED}, 400) + return Outcome(context | {"validation": body}) + + async def post(self, path: str, payload: dict[str, Any]) -> tuple[int, dict[str, Any]] | None: + """The (status, body) answer of converter-api, or None when it is unavailable.""" + try: + return await self.api.post(path, payload) + except ApiUnavailableError as exc: + logger.error("converter-api unavailable: %s", exc) + return None + + @staticmethod + def converted(status: int, body: dict[str, Any]) -> bool: + """Whether converter-api answered with a list of converted files.""" + return status == 200 and bool(body.get("success")) and isinstance(body.get("files"), list) + + @staticmethod + def rejected(context: dict[str, Any], body: dict[str, Any]) -> Outcome: + """The error converter-api gave, with its position in the input when it has one.""" + return Outcome( + context + | { + "error": body.get("error") or CONVERTER_FAILED, + "error_line": body.get("line"), + "error_column": body.get("column"), + }, + 400, + ) + + +def converter_service(request: Request) -> ConverterService: + """The ConverterService of the running app, set up by its lifespan.""" + return request.app.state.converter diff --git a/services/web/editor/src/editor.js b/services/web/editor/src/editor.js index a8ad3f2..b772e86 100644 --- a/services/web/editor/src/editor.js +++ b/services/web/editor/src/editor.js @@ -1,4 +1,5 @@ -// DevToolkit's YAML editor: CodeMirror 6, bundled by esbuild into static/vendor/editor.js. +// DevToolkit's code editor: CodeMirror 6 with YAML and HCL (Terraform) highlighting, bundled +// by esbuild into static/vendor/editor.js. // Everything visual comes from the design tokens (CSS custom properties), so the editor // follows the light/dark theme like the rest of the page. import { EditorState } from "@codemirror/state"; @@ -21,11 +22,101 @@ import { bracketMatching, foldGutter, indentUnit, + StreamLanguage, } from "@codemirror/language"; import { tags } from "@lezer/highlight"; import { lintGutter, setDiagnostics } from "@codemirror/lint"; import { yaml } from "@codemirror/lang-yaml"; +// Terraform's HCL. CodeMirror has no official HCL package, and highlighting is all the output +// panels need, so a small stream tokenizer does: comments, strings with ${...}, numbers, +// true/false/null, block types at the start of a line, and attribute names before `=`. +const HCL_BLOCKS = new Set([ + "resource", "data", "variable", "output", "locals", "module", "provider", "terraform", + "import", "moved", "removed", "check", "dynamic", "content", "lifecycle", "validation", +]); +const hcl = StreamLanguage.define({ + name: "hcl", + startState: () => ({ inString: false, depth: 0, inComment: false }), + token(stream, state) { + if (state.inComment) { + if (stream.skipTo("*/")) { + stream.match("*/"); + state.inComment = false; + } else { + stream.skipToEnd(); + } + return "comment"; + } + if (state.inString) { + if (state.depth > 0) { + // Inside ${...}: code, which can hold its own strings and braces. + if (stream.peek() === '"') { + stream.next(); + while (!stream.eol()) { + const next = stream.next(); + if (next === "\\") stream.next(); + else if (next === '"') break; + } + return "string"; + } + if (stream.match("{")) { + state.depth += 1; + return "punctuation"; + } + if (stream.match("}")) { + state.depth -= 1; + return state.depth === 0 ? "meta" : "punctuation"; + } + } else { + if (stream.match("$${") || stream.match("%%{")) return "string"; // escaped, literal + if (stream.match("${") || stream.match("%{")) { + state.depth = 1; + return "meta"; + } + while (!stream.eol()) { + const next = stream.peek(); + if (next === '"') { + stream.next(); + state.inString = false; + return "string"; + } + const after = stream.string.charAt(stream.pos + 1); + const opens = after === "{" || (after === next && stream.string.charAt(stream.pos + 2) === "{"); + if ((next === "$" || next === "%") && opens) break; + if (next === "\\") stream.next(); + stream.next(); + } + return "string"; + } + } + if (stream.eatSpace()) return null; + if (stream.match("#") || stream.match("//")) { + stream.skipToEnd(); + return "comment"; + } + if (stream.match("/*")) { + state.inComment = true; + return "comment"; + } + if (stream.peek() === '"') { + stream.next(); + state.inString = true; + return "string"; + } + if (stream.match(/^-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?/)) return "number"; + if (stream.match(/^(true|false|null)\b/)) return "bool"; + const word = stream.match(/^[A-Za-z_][A-Za-z0-9_-]*/); + if (word) { + if (stream.match(/^\s*=(?!=)/, false)) return "propertyName"; + if (HCL_BLOCKS.has(word[0]) && stream.string.slice(0, stream.start).trim() === "") return "keyword"; + return "variableName"; + } + stream.next(); + return "punctuation"; + }, +}); + const theme = EditorView.theme({ "&": { backgroundColor: "var(--color-surface-sunken)", @@ -79,7 +170,7 @@ const highlight = HighlightStyle.define([ /** * Create an editor in `parent`. - * options: { doc, readOnly, placeholder, onChange(text) } + * options: { doc, readOnly, placeholder, onChange(text), language: "yaml" | "hcl" } * returns: { view, getValue(), setValue(text), setError(line, column, message), clearErrors(), focus() } */ export function create(parent, options = {}) { @@ -99,7 +190,7 @@ export function create(parent, options = {}) { EditorState.tabSize.of(2), EditorView.lineWrapping, keymap.of([indentWithTab, ...defaultKeymap, ...historyKeymap]), - yaml(), + options.language === "hcl" ? hcl : yaml(), syntaxHighlighting(highlight), theme, ]; diff --git a/services/web/error_pages.py b/services/web/error_pages.py new file mode 100644 index 0000000..3259759 --- /dev/null +++ b/services/web/error_pages.py @@ -0,0 +1,26 @@ +"""Error pages with a way back, in place of the JSON errors of FastAPI.""" + +from __future__ import annotations + +from fastapi import Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import HTMLResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +from messages import BAD_FORM, HTTP_ERROR_MESSAGES +from rendering import page +from settings import ERROR_PAGE + + +async def http_error(request: Request, exc: StarletteHTTPException) -> HTMLResponse: + """The error page for an HTTP error, such as an unknown address.""" + # Starlette always sets the detail, at least to the status phrase. + message = HTTP_ERROR_MESSAGES.get(exc.status_code, str(exc.detail)) + return page( + request, ERROR_PAGE, {"status": exc.status_code, "message": message}, exc.status_code + ) + + +async def form_error(request: Request, exc: RequestValidationError) -> HTMLResponse: + """The error page for a form with a field FastAPI cannot read, such as a bad checkbox.""" + return page(request, ERROR_PAGE, {"status": 400, "message": BAD_FORM}, 400) diff --git a/services/web/errors.py b/services/web/errors.py new file mode 100644 index 0000000..70d1a78 --- /dev/null +++ b/services/web/errors.py @@ -0,0 +1,7 @@ +"""Exceptions of the web service.""" + +from __future__ import annotations + + +class InputError(Exception): + """The input of the user cannot be sent to converter-api. The message is shown on the page.""" diff --git a/services/web/examples.py b/services/web/examples.py new file mode 100644 index 0000000..5ea6c1a --- /dev/null +++ b/services/web/examples.py @@ -0,0 +1,272 @@ +"""The example inputs behind the "Load an example" buttons.""" + +from __future__ import annotations + +# A realistic compose file for the "Load an example" button: two services, a health check, +# a dependency and a named volume, so every kind of conversion shows up in the result. +EXAMPLE_COMPOSE = """\ +name: shop +services: + web: + image: nginx:1.27 + ports: + - "8080:80" + depends_on: + - api + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost/"] + interval: 30s + timeout: 3s + retries: 3 + api: + image: ghcr.io/example/shop-api:1.4.2 + ports: + - "3000" + environment: + DATABASE_URL: postgres://shop:shop@db:5432/shop + LOG_LEVEL: info + depends_on: + - db + deploy: + replicas: 2 + resources: + limits: + cpus: "0.5" + memory: 256M + db: + image: postgres:16 + ports: + - "5432" + environment: + POSTGRES_PASSWORD: shop + volumes: + - dbdata:/var/lib/postgresql/data +volumes: + dbdata: {} +""" + +# Examples for the CloudFormation page: one per kind of input, each small enough to read but +# with something in it for every part of the conversion (references, conditions, notes). +EXAMPLE_CLOUDFORMATION = """\ +AWSTemplateFormatVersion: "2010-09-09" +Description: Image uploads, resized by a function +Parameters: + Environment: + Type: String + Default: dev + AllowedValues: [dev, prod] + RetentionDays: + Type: Number + Default: 30 +Conditions: + IsProd: !Equals [!Ref Environment, prod] +Resources: + Uploads: + Type: AWS::S3::Bucket + DeletionPolicy: Retain + Properties: + BucketName: !Sub "${AWS::StackName}-uploads-${AWS::AccountId}" + VersioningConfiguration: + Status: !If [IsProd, Enabled, Suspended] + BucketEncryption: + ServerSideEncryptionConfiguration: + - ServerSideEncryptionByDefault: + SSEAlgorithm: AES256 + LifecycleConfiguration: + Rules: + - Id: expire-old + Status: Enabled + ExpirationInDays: !Ref RetentionDays + Tags: + - Key: environment + Value: !Ref Environment + Jobs: + Type: AWS::SQS::Queue + Properties: + VisibilityTimeout: 120 + RedrivePolicy: + deadLetterTargetArn: !GetAtt DeadLetters.Arn + maxReceiveCount: 5 + DeadLetters: + Type: AWS::SQS::Queue + Properties: + MessageRetentionPeriod: 1209600 + ResizerRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + ManagedPolicyArns: + - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole + Policies: + - PolicyName: read-uploads + PolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: s3:GetObject + Resource: !Sub "${Uploads.Arn}/*" + Resizer: + Type: AWS::Lambda::Function + Properties: + Runtime: python3.13 + Handler: index.handler + Role: !GetAtt ResizerRole.Arn + MemorySize: !If [IsProd, 1024, 256] + Timeout: 60 + Environment: + Variables: + BUCKET: !Ref Uploads + QUEUE_URL: !Ref Jobs + Code: + ZipFile: | + def handler(event, context): + return {"resized": len(event.get("Records", []))} + JobsTrigger: + Type: AWS::Lambda::EventSourceMapping + Properties: + EventSourceArn: !GetAtt Jobs.Arn + FunctionName: !Ref Resizer + BatchSize: 10 + Alerts: + Type: AWS::SNS::Topic + Condition: IsProd +Outputs: + BucketName: + Value: !Ref Uploads + QueueUrl: + Value: !Ref Jobs + Export: + Name: !Sub "${AWS::StackName}-queue-url" +""" + +EXAMPLE_SAM = """\ +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: A small orders API +Globals: + Function: + Runtime: python3.13 + Timeout: 10 + Environment: + Variables: + TABLE_NAME: !Ref Orders +Resources: + Orders: + Type: AWS::Serverless::SimpleTable + Properties: + PrimaryKey: + Name: orderId + Type: String + OrdersFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: src/orders/ + Handler: app.handler + Policies: + - DynamoDBCrudPolicy: + TableName: !Ref Orders + Events: + ListOrders: + Type: Api + Properties: + Path: /orders + Method: get + GetOrder: + Type: Api + Properties: + Path: /orders/{id} + Method: get + Nightly: + Type: Schedule + Properties: + Schedule: cron(0 3 * * ? *) +Outputs: + ApiUrl: + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/orders" +""" + +EXAMPLE_CDK = """\ +{ + "Resources": { + "NotesTable7B1C1A4B": { + "Type": "AWS::DynamoDB::Table", + "Properties": { + "AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}], + "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], + "BillingMode": "PAY_PER_REQUEST" + }, + "UpdateReplacePolicy": "Retain", + "DeletionPolicy": "Retain", + "Metadata": {"aws:cdk:path": "NotesStack/NotesTable/Resource"} + }, + "HandlerServiceRoleFCDC14AE": { + "Type": "AWS::IAM::Role", + "Properties": { + "AssumeRolePolicyDocument": { + "Statement": [{ + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": {"Service": "lambda.amazonaws.com"} + }], + "Version": "2012-10-17" + }, + "ManagedPolicyArns": [{ + "Fn::Join": ["", [ + "arn:", {"Ref": "AWS::Partition"}, + ":iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" + ]] + }] + }, + "Metadata": {"aws:cdk:path": "NotesStack/Handler/ServiceRole/Resource"} + }, + "Handler886CB40B": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "S3Bucket": {"Fn::Sub": "cdk-hnb659fds-assets-${AWS::AccountId}-${AWS::Region}"}, + "S3Key": "6c3d4a1f0e2b.zip" + }, + "Handler": "index.handler", + "Role": {"Fn::GetAtt": ["HandlerServiceRoleFCDC14AE", "Arn"]}, + "Runtime": "nodejs22.x", + "Environment": {"Variables": {"TABLE": {"Ref": "NotesTable7B1C1A4B"}}} + }, + "DependsOn": ["HandlerServiceRoleFCDC14AE"], + "Metadata": { + "aws:cdk:path": "NotesStack/Handler/Resource", + "aws:asset:path": "asset.6c3d4a1f0e2b", + "aws:asset:property": "Code" + } + }, + "CDKMetadata": { + "Type": "AWS::CDK::Metadata", + "Properties": {"Analytics": "v2:deflate64:H4sIAAAAAAAA"}, + "Metadata": {"aws:cdk:path": "NotesStack/CDKMetadata/Default"} + } + }, + "Parameters": { + "BootstrapVersion": { + "Type": "AWS::SSM::Parameter::Value", + "Default": "/cdk-bootstrap/hnb659fds/version" + } + }, + "Rules": { + "CheckBootstrapVersion": { + "Assertions": [{ + "Assert": {"Fn::Not": [{"Fn::Contains": [ + ["1", "2", "3", "4", "5"], {"Ref": "BootstrapVersion"} + ]}]}, + "AssertDescription": "CDK bootstrap stack version 6 required." + }] + } + } +} +""" + +EXAMPLES = {"cloudformation": EXAMPLE_CLOUDFORMATION, "sam": EXAMPLE_SAM, "cdk": EXAMPLE_CDK} diff --git a/services/web/inputs.py b/services/web/inputs.py new file mode 100644 index 0000000..975fbb5 --- /dev/null +++ b/services/web/inputs.py @@ -0,0 +1,65 @@ +"""Reads and checks what users submit, before anything is sent to converter-api.""" + +from __future__ import annotations + +from fastapi import UploadFile + +from errors import InputError +from messages import ( + BAD_LAYOUT, + BAD_NAMESPACE, + BAD_OUTPUT, + BAD_PROVIDER, + BAD_STACK_NAME, + EMPTY_YAML, + NOT_UTF8, + TOO_LONG, +) +from models import CfnForm, ComposeForm +from settings import ( + BYTES_PER_CHAR, + LAYOUTS, + MAX_INPUT_CHARS, + NAMESPACE_RE, + OUTPUTS, + PROVIDERS, + STACK_NAME_RE, +) + + +async def read_input( + text: str, + upload: UploadFile | None, + limit: int = MAX_INPUT_CHARS, + empty: str = EMPTY_YAML, +) -> str: + """Return the uploaded file if one was chosen, otherwise the pasted text.""" + if upload is not None and upload.filename: + raw = await upload.read(limit * BYTES_PER_CHAR + 1) + try: + text = raw.decode("utf-8-sig") + except UnicodeDecodeError as exc: + raise InputError(NOT_UTF8) from exc + if not text.strip(): + raise InputError(empty) + if len(text) > limit: + raise InputError(TOO_LONG.format(limit=limit)) + return text + + +def check_compose(form: ComposeForm) -> None: + """Raise InputError when a Compose form option has a value converter-api rejects.""" + if not NAMESPACE_RE.match(form.namespace): + raise InputError(BAD_NAMESPACE) + if form.output not in OUTPUTS: + raise InputError(BAD_OUTPUT) + + +def check_cfn(form: CfnForm) -> None: + """Raise InputError when a CloudFormation form option has a value converter-api rejects.""" + if form.stack_name and not STACK_NAME_RE.match(form.stack_name): + raise InputError(BAD_STACK_NAME) + if form.provider not in PROVIDERS: + raise InputError(BAD_PROVIDER) + if form.layout not in LAYOUTS: + raise InputError(BAD_LAYOUT) diff --git a/services/web/log_config.py b/services/web/log_config.py new file mode 100644 index 0000000..ae0328c --- /dev/null +++ b/services/web/log_config.py @@ -0,0 +1,28 @@ +"""Logging set-up from the LOG_LEVEL environment variable.""" + +from __future__ import annotations + +import logging + +from messages import UNKNOWN_LOG_LEVEL +from settings import DEFAULT_LOG_LEVEL, LOG_FORMAT, LOG_LEVELS, LOGGER_NAME + +logger = logging.getLogger(LOGGER_NAME) + + +def resolve_log_level(value: str | None) -> tuple[str, str | None]: + """Return (level, warning). An unknown LOG_LEVEL falls back to INFO and keeps running.""" + level = (value or DEFAULT_LOG_LEVEL).strip().upper() + if level in LOG_LEVELS: + return level, None + allowed = ", ".join(name.lower() for name in LOG_LEVELS) + return DEFAULT_LOG_LEVEL, UNKNOWN_LOG_LEVEL.format(value=value, allowed=allowed) + + +def configure_logging(value: str | None) -> str: + """Set up logging from a LOG_LEVEL value and return the level used.""" + level, warning = resolve_log_level(value) + logging.basicConfig(level=level, format=LOG_FORMAT) + if warning: + logger.warning(warning) + return level diff --git a/services/web/main.py b/services/web/main.py index 45ac945..8183bf3 100644 --- a/services/web/main.py +++ b/services/web/main.py @@ -1,188 +1,60 @@ -"""web: DevToolkit's web UI. Renders the pages and calls converter-api server-side.""" +"""web: the DevToolkit web UI. Renders the pages and calls converter-api on the server side. + +This module wires the app together; the routes live in routes/, the middleware in +middleware.py and the error pages in error_pages.py.""" from __future__ import annotations -import base64 -import hashlib -import io -import logging import os -import re -import zipfile -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterator from contextlib import asynccontextmanager -from pathlib import Path -from typing import Any -from fastapi import FastAPI, Form, Request, Response, UploadFile +from fastapi import FastAPI from fastapi.exceptions import RequestValidationError -from fastapi.responses import HTMLResponse, PlainTextResponse, StreamingResponse from fastapi.staticfiles import StaticFiles -from fastapi.templating import Jinja2Templates from starlette.exceptions import HTTPException as StarletteHTTPException -from api_client import ApiClient, ApiUnavailableError - -LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") - - -def resolve_log_level(value: str | None) -> tuple[str, str | None]: - """Return (level, warning). An unknown LOG_LEVEL falls back to INFO instead of crashing.""" - level = (value or "info").strip().upper() - if level in LOG_LEVELS: - return level, None - allowed = ", ".join(name.lower() for name in LOG_LEVELS) - return "INFO", f"Unknown LOG_LEVEL {value!r}; using 'info'. Allowed: {allowed}" - - -logger = logging.getLogger("web") - - -def configure_logging(value: str | None) -> str: - """Set up logging from a LOG_LEVEL value and return the level used.""" - level, warning = resolve_log_level(value) - logging.basicConfig(level=level, format="%(asctime)s %(levelname)s %(name)s %(message)s") - if warning: - logger.warning(warning) - return level - - -LOG_LEVEL = configure_logging(os.getenv("LOG_LEVEL")) - -BASE_DIR = Path(__file__).parent -# Same limit as converter-api, checked here first so users get a clear message. -MAX_INPUT_CHARS = 100_000 -# Room for the form fields and multipart framing around a maximum-size input. -MAX_BODY_BYTES = 4 * MAX_INPUT_CHARS + 16_384 -NAMESPACE_RE = re.compile(r"^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$") -OUTPUTS = ("manifests", "helm") -UNAVAILABLE = "The converter is unavailable right now. Please try again in a minute." - -# A realistic compose file for the "Load an example" button: two services, a health check, -# a dependency and a named volume, so every kind of conversion shows up in the result. -EXAMPLE_COMPOSE = """\ -name: shop -services: - web: - image: nginx:1.27 - ports: - - "8080:80" - depends_on: - - api - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost/"] - interval: 30s - timeout: 3s - retries: 3 - api: - image: ghcr.io/example/shop-api:1.4.2 - ports: - - "3000" - environment: - DATABASE_URL: postgres://shop:shop@db:5432/shop - LOG_LEVEL: info - depends_on: - - db - deploy: - replicas: 2 - resources: - limits: - cpus: "0.5" - memory: 256M - db: - image: postgres:16 - ports: - - "5432" - environment: - POSTGRES_PASSWORD: shop - volumes: - - dbdata:/var/lib/postgresql/data -volumes: - dbdata: {} -""" - -# Applies a saved theme choice before first paint, so the page never flashes the wrong theme. -# It must be inline (a deferred script is too late), so the CSP allows exactly this script by -# hash. Change the text here and the hash follows. -THEME_SCRIPT = ( - 'try{var t=localStorage.getItem("theme");' - 'if(t==="light"||t==="dark")document.documentElement.setAttribute("data-theme",t)}' - "catch(e){}" +from api_client import ApiClient +from conversions import ConverterService +from error_pages import form_error, http_error +from log_config import configure_logging +from middleware import limits_and_headers +from routes import cfn, compose, home, yaml_check +from settings import ( + API_AUTH_DEFAULT, + API_AUTH_VARIABLE, + API_URL_DEFAULT, + API_URL_VARIABLE, + LOG_LEVEL_VARIABLE, + STATIC_DIR, ) -THEME_SCRIPT_HASH = base64.b64encode(hashlib.sha256(THEME_SCRIPT.encode()).digest()).decode() - -# Scripts: only our own files plus the theme script by hash. Styles: the code editor positions -# its cursor and layers with inline style attributes and injects its own stylesheet, which a -# nonce cannot cover, so inline styles are allowed; every piece of user content is escaped. -SECURITY_HEADERS = { - "Content-Security-Policy": ( - f"default-src 'self'; script-src 'self' 'sha256-{THEME_SCRIPT_HASH}'; " - "style-src 'self' 'unsafe-inline'; img-src 'self' data:; form-action 'self'; " - "frame-ancestors 'none'; base-uri 'none'; object-src 'none'" - ), - "X-Content-Type-Options": "nosniff", - "Referrer-Policy": "no-referrer", - "X-Frame-Options": "DENY", -} -# Static URLs carry a content hash, so files can be cached for a year and a new build still -# shows up at once. HTML must never be cached: its URL stays the same while its content changes. -STATIC_CACHE = "public, max-age=31536000, immutable" -HTML_CACHE = "public, max-age=0, must-revalidate" - -_static_versions: dict[str, str] = {} - - -def static_url(name: str) -> str: - """URL for a file in static/, versioned by its content. A missing file (e.g. app.css before - `make css`) gets version 0 rather than breaking the page.""" - if name not in _static_versions: - try: - digest = hashlib.sha256((BASE_DIR / "static" / name).read_bytes()).hexdigest() - _static_versions[name] = digest[:8] - except OSError: - _static_versions[name] = "0" - return f"/static/{name}?v={_static_versions[name]}" +LOG_LEVEL = configure_logging(os.getenv(LOG_LEVEL_VARIABLE)) -templates = Jinja2Templates(directory=BASE_DIR / "templates") -templates.env.globals["theme_script"] = THEME_SCRIPT -templates.env.globals["static_url"] = static_url - -class InputError(Exception): - """The user's input can't be sent to converter-api. The message is shown on the page.""" - - -async def read_input(text: str, upload: UploadFile | None) -> str: - """Return the uploaded file if one was chosen, otherwise the pasted text.""" - if upload is not None and upload.filename: - raw = await upload.read(MAX_INPUT_CHARS * 4 + 1) - try: - text = raw.decode("utf-8-sig") - except UnicodeDecodeError as exc: - raise InputError("The uploaded file isn't UTF-8 text.") from exc - if not text.strip(): - raise InputError("Paste some YAML or choose a file to upload.") - if len(text) > MAX_INPUT_CHARS: - raise InputError(f"The input is longer than {MAX_INPUT_CHARS:,} characters.") - return text +def api_from_environment() -> ApiClient: + """A converter-api client configured by CONVERTER_API_URL and CONVERTER_API_AUTH.""" + return ApiClient( + os.getenv(API_URL_VARIABLE, API_URL_DEFAULT), + auth=os.getenv(API_AUTH_VARIABLE, API_AUTH_DEFAULT), + ) -def wants_fragment(request: Request) -> bool: - """The page's script posts forms itself and asks for just the result markup.""" - return request.headers.get("x-requested-with") == "fetch" +@asynccontextmanager +async def lifespan(app: FastAPI) -> AsyncIterator[None]: + """Hold a converter-api client while the app runs: the one given to create_app (kept in + app.state.given_api), or else one configured from the environment.""" + api = app.state.given_api + if api is None: + api = api_from_environment() + app.state.api = api + app.state.converter = ConverterService(api) + yield + await api.aclose() def create_app(api: ApiClient | None = None) -> FastAPI: - @asynccontextmanager - async def lifespan(app: FastAPI) -> AsyncIterator[None]: - app.state.api = api or ApiClient( - os.getenv("CONVERTER_API_URL", "http://localhost:8000"), - auth=os.getenv("CONVERTER_API_AUTH", "none"), - ) - yield - await app.state.api.aclose() - + """The web app. Tests pass `api` to reach a fake converter-api.""" app = FastAPI( title="DevToolkit web", docs_url=None, @@ -190,238 +62,15 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: openapi_url=None, lifespan=lifespan, ) - app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static") - - @app.middleware("http") - async def limits_and_headers( - request: Request, call_next: Callable[[Request], Awaitable[Response]] - ) -> Response: - if request.method == "POST": - length = request.headers.get("content-length") - if length is None or not length.isdigit(): - return PlainTextResponse("Content-Length required", status_code=411) - if int(length) > MAX_BODY_BYTES: - return PlainTextResponse("Request too large", status_code=413) - response = await call_next(request) - response.headers.update(SECURITY_HEADERS) - if request.url.path.startswith("/static/"): - response.headers["Cache-Control"] = STATIC_CACHE - elif response.headers.get("content-type", "").startswith("text/html"): - response.headers["Cache-Control"] = HTML_CACHE - return response - - def page( - request: Request, name: str, context: dict[str, Any], status_code: int = 200 - ) -> HTMLResponse: - return templates.TemplateResponse(request, name, context, status_code=status_code) - - def tool_page( - request: Request, name: str, fragment: str, context: dict[str, Any], status_code: int = 200 - ) -> HTMLResponse: - """The whole page for a normal post, or just the result markup for the page's script.""" - template = fragment if wants_fragment(request) else name - return page(request, template, context, status_code) - - # Error pages with a way back, instead of FastAPI's JSON. - @app.exception_handler(StarletteHTTPException) - async def http_error(request: Request, exc: StarletteHTTPException) -> HTMLResponse: - if exc.status_code == 404: - message = "There is no page at this address." - elif exc.status_code == 405: - message = "That request method isn't allowed here." - else: - message = str(exc.detail) # Starlette always sets it, at least to the status phrase - return page( - request, "error.html", {"status": exc.status_code, "message": message}, exc.status_code - ) - - @app.exception_handler(RequestValidationError) - async def form_error(request: Request, exc: RequestValidationError) -> HTMLResponse: - return page( - request, - "error.html", - {"status": 400, "message": "The form wasn't filled in correctly."}, - 400, - ) - - @app.get("/health") - def health() -> dict[str, str]: - """Liveness probe: the process is up.""" - return {"status": "healthy"} - - @app.get("/ready") - def ready() -> dict[str, str]: - """Readiness probe. Doesn't check converter-api, so one slow service can't take the - other out of rotation; pages show an error instead.""" - return {"status": "ready"} - - @app.get("/", response_class=HTMLResponse) - def index(request: Request) -> HTMLResponse: - return page(request, "index.html", {}) - - # --- Compose -> Kubernetes ------------------------------------------------------------ - - def compose_context( - compose_yaml: str, namespace: str, include_service: bool, output: str - ) -> dict[str, Any]: - return { - "compose_yaml": compose_yaml, - "namespace": namespace, - "include_service": include_service, - "output": output, - } - - @app.get("/compose-to-k8s", response_class=HTMLResponse) - def compose_form(request: Request, example: str | None = None) -> Response: - if example: - # The page's script asks for the text alone; a plain visit gets the filled form. - if "text/plain" in request.headers.get("accept", ""): - return PlainTextResponse(EXAMPLE_COMPOSE) - return page( - request, - "compose_to_k8s.html", - compose_context(EXAMPLE_COMPOSE, "shop", True, "manifests"), - ) - return page( - request, "compose_to_k8s.html", compose_context("", "default", True, "manifests") - ) - - async def convert( - request: Request, - compose_yaml: str, - compose_file: UploadFile | None, - namespace: str, - include_service: bool, - output: str, - ) -> tuple[dict[str, Any], int]: - """Run a conversion. Returns (template context, HTTP status).""" - context = compose_context(compose_yaml, namespace, include_service, output) - try: - context["compose_yaml"] = await read_input(compose_yaml, compose_file) - if not NAMESPACE_RE.match(namespace): - raise InputError( - "Namespace must be lowercase letters, digits and '-', at most 63 characters, " - "starting and ending with a letter or digit." - ) - if output not in OUTPUTS: - raise InputError("Output must be 'manifests' or 'helm'.") - except InputError as exc: - return context | {"error": str(exc)}, 400 - - try: - status, body = await request.app.state.api.post( - "/convert/compose-to-k8s/files", - { - "compose_yaml": context["compose_yaml"], - "namespace": namespace, - "include_service": include_service, - "output": output, - }, - ) - except ApiUnavailableError as exc: - logger.error("converter-api unavailable: %s", exc) - return context | {"error": UNAVAILABLE}, 502 - - if status == 200 and body.get("success") and isinstance(body.get("files"), list): - return context | {"files": body["files"], "notes": body.get("notes", [])}, 200 - error = body.get("error") or "The converter couldn't process this input." - return context | { - "error": error, - "error_line": body.get("line"), - "error_column": body.get("column"), - }, 400 - - @app.post("/compose-to-k8s", response_class=HTMLResponse) - async def compose_convert( - request: Request, - compose_yaml: str = Form(""), - compose_file: UploadFile | None = None, - namespace: str = Form("default"), - include_service: bool = Form(False), - output: str = Form("manifests"), - ) -> HTMLResponse: - context, status = await convert( - request, compose_yaml, compose_file, namespace, include_service, output - ) - return tool_page(request, "compose_to_k8s.html", "_result.html", context, status) - - @app.post("/compose-to-k8s/zip") - async def compose_zip( - request: Request, - compose_yaml: str = Form(""), - compose_file: UploadFile | None = None, - namespace: str = Form("default"), - include_service: bool = Form(False), - output: str = Form("manifests"), - ) -> Response: - """The same conversion, downloaded as a zip of the files.""" - context, status = await convert( - request, compose_yaml, compose_file, namespace, include_service, output - ) - if status != 200: - return page(request, "compose_to_k8s.html", context, status) - buffer = io.BytesIO() - with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: - for file in context["files"]: - archive.writestr(file["path"], file["content"]) - buffer.seek(0) - name = "helm-chart.zip" if output == "helm" else "kubernetes-manifests.zip" - return StreamingResponse( - buffer, - media_type="application/zip", - headers={"Content-Disposition": f'attachment; filename="{name}"'}, - ) - - # --- YAML check ----------------------------------------------------------------------- - - @app.get("/validate-yaml", response_class=HTMLResponse) - def validate_form(request: Request) -> HTMLResponse: - return page(request, "validate_yaml.html", {"yaml_text": ""}) - - @app.post("/validate-yaml", response_class=HTMLResponse) - async def validate( - request: Request, - yaml_text: str = Form(""), - yaml_file: UploadFile | None = None, - ) -> HTMLResponse: - context: dict[str, Any] = {"yaml_text": yaml_text} - try: - context["yaml_text"] = await read_input(yaml_text, yaml_file) - except InputError as exc: - return tool_page( - request, - "validate_yaml.html", - "_validation.html", - context | {"error": str(exc)}, - 400, - ) - - try: - status, body = await request.app.state.api.post( - "/validate/yaml", {"yaml": context["yaml_text"]} - ) - except ApiUnavailableError as exc: - logger.error("converter-api unavailable: %s", exc) - return tool_page( - request, - "validate_yaml.html", - "_validation.html", - context | {"error": UNAVAILABLE}, - 502, - ) - - if status != 200 or "valid" not in body: - return tool_page( - request, - "validate_yaml.html", - "_validation.html", - context | {"error": "The validator couldn't process this input."}, - 400, - ) - return tool_page( - request, "validate_yaml.html", "_validation.html", context | {"validation": body} - ) - + app.state.given_api = api + app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static") + app.middleware("http")(limits_and_headers) + app.add_exception_handler(StarletteHTTPException, http_error) + app.add_exception_handler(RequestValidationError, form_error) + app.include_router(home.router) + app.include_router(compose.router) + app.include_router(cfn.router) + app.include_router(yaml_check.router) return app diff --git a/services/web/messages.py b/services/web/messages.py new file mode 100644 index 0000000..e5ba4e7 --- /dev/null +++ b/services/web/messages.py @@ -0,0 +1,39 @@ +"""Text shown to users: error messages on the pages and the notes file in the Terraform zip.""" + +from __future__ import annotations + +UNAVAILABLE = "The converter is unavailable right now. Please try again in a minute." +NOT_UTF8 = "The uploaded file is not UTF-8 text." +EMPTY_YAML = "Paste some YAML or choose a file to upload." +EMPTY_TEMPLATE = "Paste a template or choose a file to upload." +TOO_LONG = "The input is longer than {limit:,} characters." +BAD_NAMESPACE = ( + "Namespace must be lowercase letters, digits and hyphens, at most 63 characters, " + "starting and ending with a letter or digit." +) +BAD_OUTPUT = "Output must be manifests or helm." +BAD_STACK_NAME = ( + "Stack name must start with a letter and contain only letters, digits and hyphens, " + "at most 128 characters." +) +BAD_PROVIDER = "Provider must be aws or awscc." +BAD_LAYOUT = "Layout must be files or single." +CONVERTER_FAILED = "The converter could not process this input." +VALIDATOR_FAILED = "The validator could not process this input." + +NOT_FOUND = "There is no page at this address." +METHOD_NOT_ALLOWED = "That request method is not allowed here." +BAD_FORM = "The form was not filled in correctly." +HTTP_ERROR_MESSAGES = {404: NOT_FOUND, 405: METHOD_NOT_ALLOWED} + +LENGTH_REQUIRED = "Content-Length required" +TOO_LARGE = "Request too large" + +UNKNOWN_LOG_LEVEL = 'Unknown LOG_LEVEL "{value}": using info. Allowed: {allowed}' + +NOTES_TITLE = "# Conversion notes" +NOTES_INTRO = ( + "Converted from {source} by DevToolkit. The items below need a decision; " + "everything else was converted." +) +NOTES_NONE = "- Nothing: every resource was converted." diff --git a/services/web/middleware.py b/services/web/middleware.py new file mode 100644 index 0000000..067b6f1 --- /dev/null +++ b/services/web/middleware.py @@ -0,0 +1,51 @@ +"""The HTTP middleware: request size limits, security headers and cache rules.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable + +from fastapi import Request, Response +from fastapi.responses import PlainTextResponse + +from messages import LENGTH_REQUIRED, TOO_LARGE +from security import ( + HTML_CACHE, + HTML_CONTENT_TYPE, + SECURITY_HEADERS, + STATIC_CACHE, + STATIC_PREFIX, +) +from settings import MAX_BODY_BYTES + + +async def limits_and_headers( + request: Request, call_next: Callable[[Request], Awaitable[Response]] +) -> Response: + """Refuse posts without a usable size, then add the headers to the response.""" + refusal = size_refusal(request) + if refusal is not None: + return refusal + response = await call_next(request) + add_headers(request, response) + return response + + +def size_refusal(request: Request) -> Response | None: + """The answer to a post without a Content-Length or with too large a body, else None.""" + if request.method != "POST": + return None + length = request.headers.get("content-length") + if length is None or not length.isdigit(): + return PlainTextResponse(LENGTH_REQUIRED, status_code=411) + if int(length) > MAX_BODY_BYTES: + return PlainTextResponse(TOO_LARGE, status_code=413) + return None + + +def add_headers(request: Request, response: Response) -> None: + """The security headers on every response, and the cache rule for static files and HTML.""" + response.headers.update(SECURITY_HEADERS) + if request.url.path.startswith(STATIC_PREFIX): + response.headers["Cache-Control"] = STATIC_CACHE + elif response.headers.get("content-type", "").startswith(HTML_CONTENT_TYPE): + response.headers["Cache-Control"] = HTML_CACHE diff --git a/services/web/models.py b/services/web/models.py new file mode 100644 index 0000000..33ae3c4 --- /dev/null +++ b/services/web/models.py @@ -0,0 +1,62 @@ +"""The forms of the tool pages and the outcome of handling one.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from settings import SOURCE_LABELS + + +@dataclass +class ComposeForm: + """The fields of the Compose to Kubernetes form.""" + + compose_yaml: str + namespace: str = "default" + include_service: bool = True + output: str = "manifests" + + def context(self) -> dict[str, Any]: + """The template context that fills the form with these values.""" + return { + "compose_yaml": self.compose_yaml, + "namespace": self.namespace, + "include_service": self.include_service, + "output": self.output, + } + + +@dataclass +class CfnForm: + """The fields of the CloudFormation to Terraform form.""" + + template: str + provider: str = "aws" + layout: str = "files" + stack_name: str = "" + include_imports: bool = False + + def context(self) -> dict[str, Any]: + """The template context that fills the form with these values.""" + return { + "template": self.template, + "provider": self.provider, + "layout": self.layout, + "stack_name": self.stack_name, + "include_imports": self.include_imports, + "source_labels": SOURCE_LABELS, + } + + +@dataclass +class Outcome: + """What a submitted form leads to: the template context and the HTTP status.""" + + context: dict[str, Any] + status: int = 200 + + @property + def ok(self) -> bool: + """Whether the input was handled without an error.""" + return self.status == 200 diff --git a/services/web/pyproject.toml b/services/web/pyproject.toml index 40acac5..591b913 100644 --- a/services/web/pyproject.toml +++ b/services/web/pyproject.toml @@ -1,9 +1,26 @@ [tool.pytest.ini_options] testpaths = ["tests"] -pythonpath = ["."] +pythonpath = [".", "../converter-api"] [tool.coverage.run] -source = ["main", "api_client"] +source = [ + "api_client", + "archives", + "conversions", + "error_pages", + "errors", + "examples", + "inputs", + "log_config", + "main", + "messages", + "middleware", + "models", + "rendering", + "routes", + "security", + "settings", +] [tool.ruff] line-length = 100 diff --git a/services/web/rendering.py b/services/web/rendering.py new file mode 100644 index 0000000..01e128b --- /dev/null +++ b/services/web/rendering.py @@ -0,0 +1,64 @@ +"""Renders the Jinja templates: whole pages, or just the result markup for the page script.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Any + +from fastapi import Request +from fastapi.responses import HTMLResponse +from fastapi.templating import Jinja2Templates + +from models import Outcome +from security import THEME_SCRIPT +from settings import FRAGMENT_HEADER, FRAGMENT_VALUE, STATIC_DIR, TEMPLATES_DIR + + +class StaticVersions: + """Versions the URLs of the files in static/ by their content.""" + + def __init__(self, directory: Path) -> None: + """Version the files in `directory`.""" + self.directory = directory + self.versions: dict[str, str] = {} + + def url(self, name: str) -> str: + """URL for a file in static/, versioned by its content. A missing file (e.g. app.css + before `make css`) gets version 0 and the page still renders.""" + if name not in self.versions: + try: + digest = hashlib.sha256((self.directory / name).read_bytes()).hexdigest() + self.versions[name] = digest[:8] + except OSError: + self.versions[name] = "0" + return f"/static/{name}?v={self.versions[name]}" + + +static_versions = StaticVersions(STATIC_DIR) +templates = Jinja2Templates(directory=TEMPLATES_DIR) +templates.env.globals["theme_script"] = THEME_SCRIPT +templates.env.globals["static_url"] = static_versions.url + + +def page( + request: Request, name: str, context: dict[str, Any], status_code: int = 200 +) -> HTMLResponse: + """The template `name` rendered with `context`.""" + return templates.TemplateResponse(request, name, context, status_code=status_code) + + +def wants_fragment(request: Request) -> bool: + """The page script posts forms itself and asks for just the result markup.""" + return request.headers.get(FRAGMENT_HEADER) == FRAGMENT_VALUE + + +def wants_plain_text(request: Request) -> bool: + """The page script asks for an example as plain text; a plain visit gets the filled form.""" + return "text/plain" in request.headers.get("accept", "") + + +def tool_page(request: Request, name: str, fragment: str, outcome: Outcome) -> HTMLResponse: + """The whole page for a normal post, or just the result markup for the page script.""" + template = fragment if wants_fragment(request) else name + return page(request, template, outcome.context, outcome.status) diff --git a/services/web/routes/__init__.py b/services/web/routes/__init__.py new file mode 100644 index 0000000..d98902b --- /dev/null +++ b/services/web/routes/__init__.py @@ -0,0 +1 @@ +"""The routes of the web service, one APIRouter module per area of the site.""" diff --git a/services/web/routes/cfn.py b/services/web/routes/cfn.py new file mode 100644 index 0000000..3d84355 --- /dev/null +++ b/services/web/routes/cfn.py @@ -0,0 +1,63 @@ +"""The CloudFormation to Terraform page.""" + +from __future__ import annotations + +from fastapi import APIRouter, Form, Request, Response, UploadFile +from fastapi.responses import HTMLResponse, PlainTextResponse + +from archives import notes_file, zip_download +from conversions import converter_service +from examples import EXAMPLE_CLOUDFORMATION, EXAMPLES +from models import CfnForm +from rendering import page, tool_page, wants_plain_text +from settings import CFN_PAGE, CFN_RESULT, TERRAFORM_ZIP_NAME + +router = APIRouter() + + +@router.get("/cfn-to-terraform", response_class=HTMLResponse) +def cfn_form(request: Request, example: str | None = None) -> Response: + """The empty form, or the form filled with an example (as plain text for the page script). + An unknown example name gets the CloudFormation example.""" + if not example: + return page(request, CFN_PAGE, CfnForm("").context()) + text = EXAMPLES.get(example, EXAMPLE_CLOUDFORMATION) + if wants_plain_text(request): + return PlainTextResponse(text) + return page(request, CFN_PAGE, CfnForm(text).context()) + + +@router.post("/cfn-to-terraform", response_class=HTMLResponse) +async def cfn_convert( + request: Request, + template: str = Form(""), + template_file: UploadFile | None = None, + provider: str = Form("aws"), + layout: str = Form("files"), + stack_name: str = Form(""), + include_imports: bool = Form(False), +) -> HTMLResponse: + """Convert the posted template and show the result.""" + form = CfnForm(template, provider, layout, stack_name.strip(), include_imports) + outcome = await converter_service(request).cfn(form, template_file) + return tool_page(request, CFN_PAGE, CFN_RESULT, outcome) + + +@router.post("/cfn-to-terraform/zip") +async def cfn_zip( + request: Request, + template: str = Form(""), + template_file: UploadFile | None = None, + provider: str = Form("aws"), + layout: str = Form("files"), + stack_name: str = Form(""), + include_imports: bool = Form(False), +) -> Response: + """The same conversion, downloaded as a zip of the .tf files and the notes.""" + form = CfnForm(template, provider, layout, stack_name.strip(), include_imports) + outcome = await converter_service(request).cfn(form, template_file) + if not outcome.ok: + return page(request, CFN_PAGE, outcome.context, outcome.status) + context = outcome.context + files = context["files"] + [notes_file(context["notes"], context["source"])] + return zip_download(files, TERRAFORM_ZIP_NAME) diff --git a/services/web/routes/compose.py b/services/web/routes/compose.py new file mode 100644 index 0000000..7e2ca40 --- /dev/null +++ b/services/web/routes/compose.py @@ -0,0 +1,58 @@ +"""The Compose to Kubernetes page.""" + +from __future__ import annotations + +from fastapi import APIRouter, Form, Request, Response, UploadFile +from fastapi.responses import HTMLResponse, PlainTextResponse + +from archives import zip_download +from conversions import converter_service +from examples import EXAMPLE_COMPOSE +from models import ComposeForm +from rendering import page, tool_page, wants_plain_text +from settings import COMPOSE_PAGE, COMPOSE_RESULT, HELM_ZIP_NAME, MANIFESTS_ZIP_NAME + +router = APIRouter() + + +@router.get("/compose-to-k8s", response_class=HTMLResponse) +def compose_form(request: Request, example: str | None = None) -> Response: + """The empty form, or the form filled with the example (as plain text for the page script).""" + if not example: + return page(request, COMPOSE_PAGE, ComposeForm("").context()) + if wants_plain_text(request): + return PlainTextResponse(EXAMPLE_COMPOSE) + return page(request, COMPOSE_PAGE, ComposeForm(EXAMPLE_COMPOSE, "shop").context()) + + +@router.post("/compose-to-k8s", response_class=HTMLResponse) +async def compose_convert( + request: Request, + compose_yaml: str = Form(""), + compose_file: UploadFile | None = None, + namespace: str = Form("default"), + include_service: bool = Form(False), + output: str = Form("manifests"), +) -> HTMLResponse: + """Convert the posted Compose file and show the result.""" + form = ComposeForm(compose_yaml, namespace, include_service, output) + outcome = await converter_service(request).compose(form, compose_file) + return tool_page(request, COMPOSE_PAGE, COMPOSE_RESULT, outcome) + + +@router.post("/compose-to-k8s/zip") +async def compose_zip( + request: Request, + compose_yaml: str = Form(""), + compose_file: UploadFile | None = None, + namespace: str = Form("default"), + include_service: bool = Form(False), + output: str = Form("manifests"), +) -> Response: + """The same conversion, downloaded as a zip of the files.""" + form = ComposeForm(compose_yaml, namespace, include_service, output) + outcome = await converter_service(request).compose(form, compose_file) + if not outcome.ok: + return page(request, COMPOSE_PAGE, outcome.context, outcome.status) + name = HELM_ZIP_NAME if output == "helm" else MANIFESTS_ZIP_NAME + return zip_download(outcome.context["files"], name) diff --git a/services/web/routes/home.py b/services/web/routes/home.py new file mode 100644 index 0000000..7a8aed7 --- /dev/null +++ b/services/web/routes/home.py @@ -0,0 +1,30 @@ +"""The home page and the health probes.""" + +from __future__ import annotations + +from fastapi import APIRouter, Request +from fastapi.responses import HTMLResponse + +from rendering import page +from settings import INDEX_PAGE + +router = APIRouter() + + +@router.get("/health") +def health() -> dict[str, str]: + """Liveness probe: the process is up.""" + return {"status": "healthy"} + + +@router.get("/ready") +def ready() -> dict[str, str]: + """Readiness probe. It leaves converter-api unchecked, so one slow service keeps the other + in rotation; pages show an error instead.""" + return {"status": "ready"} + + +@router.get("/", response_class=HTMLResponse) +def index(request: Request) -> HTMLResponse: + """The home page, with a card for each tool.""" + return page(request, INDEX_PAGE, {}) diff --git a/services/web/routes/yaml_check.py b/services/web/routes/yaml_check.py new file mode 100644 index 0000000..113fe0e --- /dev/null +++ b/services/web/routes/yaml_check.py @@ -0,0 +1,29 @@ +"""The YAML check page.""" + +from __future__ import annotations + +from fastapi import APIRouter, Form, Request, UploadFile +from fastapi.responses import HTMLResponse + +from conversions import converter_service +from rendering import page, tool_page +from settings import YAML_PAGE, YAML_RESULT + +router = APIRouter() + + +@router.get("/validate-yaml", response_class=HTMLResponse) +def validate_form(request: Request) -> HTMLResponse: + """The empty form.""" + return page(request, YAML_PAGE, {"yaml_text": ""}) + + +@router.post("/validate-yaml", response_class=HTMLResponse) +async def validate( + request: Request, + yaml_text: str = Form(""), + yaml_file: UploadFile | None = None, +) -> HTMLResponse: + """Check the posted YAML and show the result.""" + outcome = await converter_service(request).validate_yaml(yaml_text, yaml_file) + return tool_page(request, YAML_PAGE, YAML_RESULT, outcome) diff --git a/services/web/security.py b/services/web/security.py new file mode 100644 index 0000000..ec849da --- /dev/null +++ b/services/web/security.py @@ -0,0 +1,36 @@ +"""The security headers and cache rules every response gets.""" + +from __future__ import annotations + +import base64 +import hashlib + +# Applies a saved theme choice before first paint, so the page never flashes the wrong theme. +# It must be inline (a deferred script is too late), so the CSP allows exactly this script by +# hash. Change the text here and the hash follows. +THEME_SCRIPT = ( + 'try{var t=localStorage.getItem("theme");' + 'if(t==="light"||t==="dark")document.documentElement.setAttribute("data-theme",t)}' + "catch(e){}" +) +THEME_SCRIPT_HASH = base64.b64encode(hashlib.sha256(THEME_SCRIPT.encode()).digest()).decode() + +# Scripts: only our own files plus the theme script by hash. Styles: the code editor positions +# its cursor and layers with inline style attributes and injects its own stylesheet, which a +# nonce cannot cover, so inline styles are allowed; every piece of user content is escaped. +SECURITY_HEADERS = { + "Content-Security-Policy": ( + f"default-src 'self'; script-src 'self' 'sha256-{THEME_SCRIPT_HASH}'; " + "style-src 'self' 'unsafe-inline'; img-src 'self' data:; form-action 'self'; " + "frame-ancestors 'none'; base-uri 'none'; object-src 'none'" + ), + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY", +} +# Static URLs carry a content hash, so files can be cached for a year and a new build still +# shows up at once. HTML is always revalidated: its URL stays the same while its content changes. +STATIC_CACHE = "public, max-age=31536000, immutable" +HTML_CACHE = "public, max-age=0, must-revalidate" +STATIC_PREFIX = "/static/" +HTML_CONTENT_TYPE = "text/html" diff --git a/services/web/settings.py b/services/web/settings.py new file mode 100644 index 0000000..ba1b094 --- /dev/null +++ b/services/web/settings.py @@ -0,0 +1,68 @@ +"""Settings of the web service: paths, input limits, accepted form values and log levels.""" + +from __future__ import annotations + +import re +from pathlib import Path + +BASE_DIR = Path(__file__).parent +TEMPLATES_DIR = BASE_DIR / "templates" +STATIC_DIR = BASE_DIR / "static" + +# Where converter-api runs and how to authenticate to it, read from the environment. +API_URL_VARIABLE = "CONVERTER_API_URL" +API_URL_DEFAULT = "http://localhost:8000" +API_AUTH_VARIABLE = "CONVERTER_API_AUTH" +API_AUTH_DEFAULT = "none" + +LOG_LEVEL_VARIABLE = "LOG_LEVEL" +LOG_LEVELS = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL") +DEFAULT_LOG_LEVEL = "INFO" +LOG_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s" +LOGGER_NAME = "web" + +# Same limits as converter-api, checked here first so users get a clear message. +MAX_INPUT_CHARS = 100_000 +MAX_TEMPLATE_CHARS = 500_000 +# Room for the form fields and multipart framing around the largest input. +MAX_BODY_BYTES = 4 * MAX_TEMPLATE_CHARS + 16_384 +# An upload may hold up to four bytes per character. +BYTES_PER_CHAR = 4 + +NAMESPACE_RE = re.compile(r"^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$") +STACK_NAME_RE = re.compile(r"^[A-Za-z][-A-Za-z0-9]{0,127}$") +OUTPUTS = ("manifests", "helm") +PROVIDERS = ("aws", "awscc") +LAYOUTS = ("files", "single") + +# converter-api paths. +COMPOSE_API_PATH = "/convert/compose-to-k8s/files" +CFN_API_PATH = "/convert/cfn-to-terraform" +VALIDATE_API_PATH = "/validate/yaml" + +# How the page script asks for the result markup alone. +FRAGMENT_HEADER = "x-requested-with" +FRAGMENT_VALUE = "fetch" + +SOURCE_LABELS = { + "cloudformation": "CloudFormation", + "sam": "AWS SAM", + "cdk": "AWS CDK (synthesized)", +} +DEFAULT_SOURCE = "cloudformation" + +# Zip downloads. +HELM_ZIP_NAME = "helm-chart.zip" +MANIFESTS_ZIP_NAME = "kubernetes-manifests.zip" +TERRAFORM_ZIP_NAME = "terraform.zip" +NOTES_FILE_NAME = "CONVERSION_NOTES.md" + +# Templates. +INDEX_PAGE = "index.html" +ERROR_PAGE = "error.html" +COMPOSE_PAGE = "compose_to_k8s.html" +COMPOSE_RESULT = "_result.html" +CFN_PAGE = "cfn_to_terraform.html" +CFN_RESULT = "_terraform_result.html" +YAML_PAGE = "validate_yaml.html" +YAML_RESULT = "_validation.html" diff --git a/services/web/static/app.js b/services/web/static/app.js index 895ebf5..2c92594 100644 --- a/services/web/static/app.js +++ b/services/web/static/app.js @@ -75,7 +75,9 @@ if (pre.dataset.mounted) return; const holder = document.createElement("div"); holder.className = "editor"; - Editor.create(holder, { doc: pre.textContent, readOnly: true }); + const path = pre.closest("[data-path]")?.dataset.path || ""; + const language = path.endsWith(".tf") ? "hcl" : "yaml"; + Editor.create(holder, { doc: pre.textContent, readOnly: true, language }); pre.dataset.mounted = "true"; pre.hidden = true; // kept for Copy and Download, which read its text pre.insertAdjacentElement("afterend", holder); @@ -174,16 +176,15 @@ }); }); - // Load an example without leaving the page. - const example = form.querySelector("[data-load-example]"); - if (example) { + // Load an example without leaving the page (a page can offer several). + form.querySelectorAll("[data-load-example]").forEach((example) => { example.addEventListener("click", async (event) => { if (!inputEditor) return; event.preventDefault(); const response = await fetch(example.href, { headers: { Accept: "text/plain" } }); if (response.ok) inputEditor.setValue(await response.text()); }); - } + }); form.querySelectorAll("[data-editor]").forEach(mountInputEditor); if (target) enhanceResult(target); @@ -206,7 +207,8 @@ const download = event.target.closest("[data-download]"); if (download) { const text = document.getElementById(download.dataset.download).textContent; - const url = URL.createObjectURL(new Blob([text], { type: "application/yaml" })); + const type = download.dataset.filename.endsWith(".tf") ? "text/plain" : "application/yaml"; + const url = URL.createObjectURL(new Blob([text], { type })); const link = Object.assign(document.createElement("a"), { href: url, download: download.dataset.filename }); link.click(); URL.revokeObjectURL(url); diff --git a/services/web/styles/input.css b/services/web/styles/input.css index c301f4f..64e942d 100644 --- a/services/web/styles/input.css +++ b/services/web/styles/input.css @@ -233,6 +233,14 @@ .tag { @apply inline-flex items-center gap-1 rounded-full bg-accent-soft px-3 py-1 text-small font-medium text-ink-on-accent-soft; } + /* Counts and labels that are not a call to act: same tag, no accent. */ + .tag-neutral { + @apply bg-surface-sunken text-ink-muted; + } + /* Something the tool could not do. */ + .tag-danger { + @apply bg-danger-soft text-ink-on-danger-soft; + } .nav-link { @apply inline-flex min-h-11 items-center gap-2 text-small text-ink-muted hover:text-ink; } diff --git a/services/web/templates/_files.html b/services/web/templates/_files.html new file mode 100644 index 0000000..0cce4bf --- /dev/null +++ b/services/web/templates/_files.html @@ -0,0 +1,24 @@ +
+ +
+ {% for file in files %} +
+
+

{{ file.path }}

+
+ + +
+
+
{{ file.content }}
+
+ {% endfor %} +
+
diff --git a/services/web/templates/_result.html b/services/web/templates/_result.html index b56e531..e8f6517 100644 --- a/services/web/templates/_result.html +++ b/services/web/templates/_result.html @@ -1,29 +1,7 @@ {% include "_messages.html" %} {% if files %} -
- -
- {% for file in files %} -
-
-

{{ file.path }}

-
- - -
-
-
{{ file.content }}
-
- {% endfor %} -
-
+{% set files_label = 'Helm chart' if output == 'helm' else '' %} +{% include "_files.html" %} {% if notes %}

{% include "icons/info.svg" %} Needs a decision ({{ notes|length }})

diff --git a/services/web/templates/_terraform_result.html b/services/web/templates/_terraform_result.html new file mode 100644 index 0000000..eac80fc --- /dev/null +++ b/services/web/templates/_terraform_result.html @@ -0,0 +1,50 @@ +{% include "_messages.html" %} +{% if files %} +
+ {% include "icons/layers.svg" %} {{ source_labels.get(source, source) }} + {{ summary.resources }} resource{{ '' if summary.resources == 1 else 's' }}: + {% if summary.aws %}{{ summary.aws }} aws{% endif %} + {% if summary.awscc %}{{ summary.awscc }} awscc{% endif %} + {% if summary.unsupported %}{{ summary.unsupported }} not converted{% endif %} +
+{% set files_label = '' %} +{% set files_stacked = true %} +{% include "_files.html" %} +{% if resources %} +
+ {% include "icons/list-tree.svg" %} Where each resource went ({{ resources|length }}) +
+ + + + + + {% for resource in resources %} + + + + + + {% endfor %} + +
CloudFormationTypeTerraform
{{ resource.logical_id }}{{ resource.type }}{% if resource.address %}{{ resource.address }}{% else %}not converted{% endif %}
+
+
+{% endif %} +{% if notes %} +
+

{% include "icons/info.svg" %} Needs a decision ({{ notes|length }})

+

Everything else was converted. These need you. The zip includes them as CONVERSION_NOTES.md.

+
    + {% for note in notes %}
  • {{ note }}
  • {% endfor %} +
+
+{% endif %} +{% elif not error %} +
+
+ {% include "icons/folder-open.svg" %} +

Your Terraform files appear here: versions.tf, variables.tf, main.tf and outputs.tf.

+
+
+{% endif %} diff --git a/services/web/templates/base.html b/services/web/templates/base.html index a876203..275154c 100644 --- a/services/web/templates/base.html +++ b/services/web/templates/base.html @@ -17,6 +17,7 @@ DevToolkit Compose → Kubernetes + CloudFormation → Terraform YAML check
{% include "icons/github.svg" %} diff --git a/services/web/templates/cfn_to_terraform.html b/services/web/templates/cfn_to_terraform.html new file mode 100644 index 0000000..609d80b --- /dev/null +++ b/services/web/templates/cfn_to_terraform.html @@ -0,0 +1,73 @@ +{% extends "base.html" %} +{% block title %}CloudFormation → Terraform · DevToolkit{% endblock %} +{% block description %}Convert CloudFormation, AWS SAM and AWS CDK templates into Terraform, with notes on everything that needs a decision.{% endblock %} +{% block content %} +
+
+

CloudFormation → Terraform

+

CloudFormation, AWS SAM and cdk synth templates in JSON or YAML. References become Terraform expressions, SAM shortcuts expand the way SAM expands them and whatever converts only in part is listed for you to decide.

+
+
+ +
+
+
+

template.yaml

+
+ {% include "icons/wand-sparkles.svg" %}Load an example: + CloudFormation + SAM + CDK + +
+
+
+ +
+

Drop a file onto the editor or press Ctrl+Enter to convert. For a CDK app, run cdk synth and convert cdk.out/<Stack>.template.json.

+ +
+
+
+ Provider +
+ + +
+
+
+ Files +
+ + +
+
+
+
+ + + +
+

The stack name is the default for var.stack_name, which stands in for AWS::StackName. Import blocks let Terraform adopt what the stack created.

+
+
+ +
+
+

terraform

+ +
+
+ {% include "_terraform_result.html" %} +
+
+
+{% endblock %} diff --git a/services/web/templates/compose_to_k8s.html b/services/web/templates/compose_to_k8s.html index 6be3f7a..d3df1f9 100644 --- a/services/web/templates/compose_to_k8s.html +++ b/services/web/templates/compose_to_k8s.html @@ -23,7 +23,7 @@

docker-compose.y
-

Drop a file onto the editor, or press Ctrl+Enter to convert.

+

Drop a file onto the editor or press Ctrl+Enter to convert.