From 61aac6f094170bad55cd11b85ccbf00fc23c7be9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:07:14 +0000 Subject: [PATCH 1/5] Rewrite the web page copy for human readers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F --- services/web/messages.py | 41 +++++++++-------- services/web/templates/_result.html | 6 +-- services/web/templates/_terraform_result.html | 6 +-- services/web/templates/_validation.html | 2 +- services/web/templates/base.html | 6 +-- services/web/templates/cfn_to_terraform.html | 18 ++++---- services/web/templates/compose_to_k8s.html | 8 ++-- services/web/templates/index.html | 11 ++--- services/web/templates/validate_yaml.html | 6 +-- services/web/tests/test_pages.py | 46 +++++++++---------- 10 files changed, 77 insertions(+), 73 deletions(-) diff --git a/services/web/messages.py b/services/web/messages.py index e5ba4e7..71b8eb4 100644 --- a/services/web/messages.py +++ b/services/web/messages.py @@ -3,37 +3,42 @@ 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." +NOT_UTF8 = "DevToolkit reads UTF-8 text files. Save the file as UTF-8 and upload it again." 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." +TOO_LONG = "This is too long to convert. The limit is {limit:,} characters." BAD_NAMESPACE = ( - "Namespace must be lowercase letters, digits and hyphens, at most 63 characters, " - "starting and ending with a letter or digit." + "Use a namespace of up to 63 lowercase letters, digits and hyphens " + "that starts and ends with a letter or digit." ) -BAD_OUTPUT = "Output must be manifests or helm." +BAD_OUTPUT = "Choose Manifests or Helm chart as the output." BAD_STACK_NAME = ( - "Stack name must start with a letter and contain only letters, digits and hyphens, " - "at most 128 characters." + "Use a stack name of up to 128 letters, digits and hyphens that starts with a letter." +) +BAD_PROVIDER = "Choose aws or awscc as the Terraform provider." +BAD_LAYOUT = "Choose split files or one main.tf as the file layout." +CONVERTER_FAILED = ( + "Something went wrong while converting this file. Try again. " + "If it keeps happening, please open an issue on GitHub." +) +VALIDATOR_FAILED = ( + "Something went wrong while checking this file. Try again. " + "If it keeps happening, please open an issue on GitHub." ) -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." +NOT_FOUND = "We could not find that page." +METHOD_NOT_ALLOWED = "This address only works through the form on its page." +BAD_FORM = "Some fields are missing or invalid. Check the form and try again." HTTP_ERROR_MESSAGES = {404: NOT_FOUND, 405: METHOD_NOT_ALLOWED} LENGTH_REQUIRED = "Content-Length required" -TOO_LARGE = "Request too large" +TOO_LARGE = "The request is 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." + "DevToolkit converted this {source} template to Terraform. " + "Review these items before you apply it." ) -NOTES_NONE = "- Nothing: every resource was converted." +NOTES_NONE = "- Nothing to review. Every resource converted as it is." diff --git a/services/web/templates/_result.html b/services/web/templates/_result.html index e8f6517..a42d806 100644 --- a/services/web/templates/_result.html +++ b/services/web/templates/_result.html @@ -4,8 +4,8 @@ {% include "_files.html" %} {% if notes %}
-

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

-

Everything else was converted. These need you.

+

{% include "icons/info.svg" %} Review before you deploy ({{ notes|length }})

+

Each item needs a decision from you. Everything else converted as it is.

    {% for note in notes %}
  • {{ note }}
  • {% endfor %}
@@ -15,7 +15,7 @@

{% include "i
{% include "icons/folder-open.svg" %} -

Your Kubernetes files appear here, one per resource.

+

Your Kubernetes files show up here.

{% endif %} diff --git a/services/web/templates/_terraform_result.html b/services/web/templates/_terraform_result.html index eac80fc..25bd591 100644 --- a/services/web/templates/_terraform_result.html +++ b/services/web/templates/_terraform_result.html @@ -33,8 +33,8 @@ {% 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.

+

{% include "icons/info.svg" %} Review before you deploy ({{ notes|length }})

+

Each item needs a decision from you. Everything else converted as it is. The zip download includes this list as CONVERSION_NOTES.md.

    {% for note in notes %}
  • {{ note }}
  • {% endfor %}
@@ -44,7 +44,7 @@

{% include "i
{% include "icons/folder-open.svg" %} -

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

+

Your Terraform files show up here.

{% endif %} diff --git a/services/web/templates/_validation.html b/services/web/templates/_validation.html index a4e31da..e1e60f8 100644 --- a/services/web/templates/_validation.html +++ b/services/web/templates/_validation.html @@ -3,7 +3,7 @@ {% if validation.valid %}
{% include "icons/circle-check.svg" %} - Valid YAML: {{ validation.documents }} document{{ '' if validation.documents == 1 else 's' }}. + The YAML is valid ({{ validation.documents }} document{{ '' if validation.documents == 1 else 's' }}).
{% else %} -

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.

+

Drop a file onto the editor or press Ctrl+Enter to convert. Using CDK? Run cdk synth and paste cdk.out/<Stack>.template.json.

- Provider + Terraform provider
- +
- Files + File layout
- - + +
@@ -52,11 +52,11 @@

template.yaml

-

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.

+

The stack name fills in AWS::StackName through var.stack_name. Import blocks let Terraform take over the resources your stack already created.

diff --git a/services/web/templates/compose_to_k8s.html b/services/web/templates/compose_to_k8s.html index d3df1f9..6647bf3 100644 --- a/services/web/templates/compose_to_k8s.html +++ b/services/web/templates/compose_to_k8s.html @@ -1,11 +1,11 @@ {% extends "base.html" %} {% block title %}Docker Compose → Kubernetes · DevToolkit{% endblock %} -{% block description %}Convert a docker-compose file into Kubernetes manifests or a Helm chart, one file per resource.{% endblock %} +{% block description %}Convert a Docker Compose file into Kubernetes manifests or a Helm chart.{% endblock %} {% block content %}

Docker Compose → Kubernetes

-

Health checks become probes, depends_on becomes init containers, named volumes become claims. Only what your file needs is generated.

+

Paste your Compose file to get Kubernetes manifests or a Helm chart. Health checks turn into probes, depends_on into init containers and named volumes into persistent volume claims. You get only the resources your services use.

@@ -39,7 +39,7 @@

docker-compose.y @@ -47,7 +47,7 @@

docker-compose.y
-

output

+

kubernetes

diff --git a/services/web/templates/index.html b/services/web/templates/index.html index 9af9b2f..b8527f1 100644 --- a/services/web/templates/index.html +++ b/services/web/templates/index.html @@ -1,9 +1,8 @@ {% extends "base.html" %} {% block content %}
- {% include "icons/wand-sparkles.svg" %} Free, in the browser, no sign-up -

DevToolkit

-

Converters for infrastructure configs. Open source, nothing stored.

+

DevToolkit

+

Move infrastructure code from one tool to another. Paste a Docker Compose file or a CloudFormation template and get Kubernetes manifests or Terraform back, with a short list of anything you need to finish yourself.

@@ -12,19 +11,19 @@

{% include "icons/boxes.svg" %}

Docker Compose → Kubernetes

-

One file per resource or a Helm chart. Health checks become probes, depends_on becomes init containers, named volumes become claims.

+

Turn a Compose file into Kubernetes manifests or a Helm chart. Health checks turn into probes, depends_on into init containers and named volumes into persistent volume claims.

Open {% include "icons/arrow-right.svg" %} {% include "icons/layers.svg" %}

CloudFormation → Terraform

-

CloudFormation, AWS SAM and cdk synth templates. Parameters become variables, !Ref and !Sub become expressions, SAM functions become the resources SAM would create.

+

Turn a CloudFormation, AWS SAM or CDK template into Terraform. Parameters turn into variables, !Ref and !Sub into Terraform expressions and each SAM function into the resources SAM would deploy for it.

Open {% include "icons/arrow-right.svg" %}
{% include "icons/file-check.svg" %}

YAML check

-

Finds the first syntax error and marks the exact line and column in the editor. Multi-document files are supported.

+

Check a YAML file for syntax errors. The editor highlights the first one at its exact line and column.

Open {% include "icons/arrow-right.svg" %}
diff --git a/services/web/templates/validate_yaml.html b/services/web/templates/validate_yaml.html index 607c9c4..e721007 100644 --- a/services/web/templates/validate_yaml.html +++ b/services/web/templates/validate_yaml.html @@ -1,9 +1,9 @@ {% extends "base.html" %} {% block title %}YAML check · DevToolkit{% endblock %} -{% block description %}Check YAML syntax. The first error is marked at its exact line and column.{% endblock %} +{% block description %}Check a YAML file for syntax errors and see exactly where the first one is.{% endblock %} {% block content %}

YAML check

-

Syntax only. The first error is marked at its line and column. Multi-document files (separated by ---) are supported.

+

Paste YAML to check its syntax. When something is wrong, the editor highlights the first error at its line and column. Files with several documents separated by --- work too.

@@ -17,7 +17,7 @@

input.yaml

-

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

+

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

{% include "_validation.html" %} diff --git a/services/web/tests/test_pages.py b/services/web/tests/test_pages.py index d5f30ec..472d54f 100644 --- a/services/web/tests/test_pages.py +++ b/services/web/tests/test_pages.py @@ -86,7 +86,7 @@ def test_probes(client): def test_index_names_the_product_and_lists_the_tools(client): html = client.get("/").text assert "DevToolkit

" in html - assert "Converters for infrastructure configs. Open source, nothing stored." in html + assert "Move infrastructure code from one tool to another." in html assert 'href="/compose-to-k8s" class="card' in html assert 'href="/validate-yaml" class="card' in html assert html.count("= 6 # icons are inlined, not fetched @@ -150,14 +150,14 @@ def test_404_page_has_a_way_back(client): response = client.get("/no-such-page") assert response.status_code == 404 assert response.headers["content-type"].startswith("text/html") - assert "There is no page at this address." in response.text + assert "We could not find that page." in response.text assert 'href="/"' in response.text def test_405_page(client): response = client.post("/", content=b"", headers={"Content-Length": "0"}) assert response.status_code == 405 - assert "is not allowed here" in response.text + assert "only works through the form" in response.text def test_malformed_form_gets_an_html_error(client, fake_api): @@ -165,7 +165,7 @@ def test_malformed_form_gets_an_html_error(client, fake_api): "/compose-to-k8s", data={"compose_yaml": COMPOSE, "include_service": "maybe"} ) assert response.status_code == 400 - assert "was not filled in correctly" in response.text + assert "Some fields are missing or invalid" in response.text assert fake_api.requests == [] @@ -213,7 +213,7 @@ def test_compose_convert_renders_files_tabs_and_notes(client, fake_api): assert "web-deployment.yaml" in html and "web-service.yaml" in html assert "kind: Deployment" in html and "kind: Service" in html assert "placeholder requests were added" in html - assert "Needs a decision (1)" in html + assert "Review before you deploy (1)" in html assert "data-zip>" in html # the zip button is shown once there are files # The form keeps what the user typed. assert 'value="shop"' in html @@ -269,7 +269,7 @@ def test_upload_not_utf8(client, fake_api): files={"compose_file": ("x.yaml", b"\xff\xfe\x00bad", "text/yaml")}, ) assert response.status_code == 400 - assert "is not UTF-8 text." in response.text + assert "reads UTF-8 text files" in response.text assert fake_api.requests == [] @@ -277,9 +277,9 @@ def test_upload_not_utf8(client, fake_api): ("data", "message"), [ ({"compose_yaml": " \n"}, "Paste some YAML"), - ({"compose_yaml": "a" * (MAX_INPUT_CHARS + 1)}, "longer than"), - ({"compose_yaml": COMPOSE, "namespace": "Bad_NS"}, "Namespace must be"), - ({"compose_yaml": COMPOSE, "output": "kustomize"}, "Output must be"), + ({"compose_yaml": "a" * (MAX_INPUT_CHARS + 1)}, "too long to convert"), + ({"compose_yaml": COMPOSE, "namespace": "Bad_NS"}, "Use a namespace"), + ({"compose_yaml": COMPOSE, "output": "kustomize"}, "Choose Manifests or Helm chart"), ], ) def test_input_rejected_before_calling_api(client, fake_api, data, message): @@ -327,7 +327,7 @@ def test_compose_unexpected_api_answer(client, fake_api): fake_api.body = {"detail": [{"msg": "..."}]} response = client.post("/compose-to-k8s", data={"compose_yaml": COMPOSE}) assert response.status_code == 400 - assert "could not process this input" in response.text + assert "Something went wrong while" in response.text def test_compose_success_without_files_list_is_an_error(client, fake_api): @@ -433,14 +433,14 @@ def test_validate_valid(client, fake_api): response = client.post("/validate-yaml", data={"yaml_text": "a: 1\n---\nb: 2\n"}) assert response.status_code == 200 assert fake_api.requests == [("/validate/yaml", {"yaml": "a: 1\n---\nb: 2\n"})] - assert "Valid YAML: 2 documents." in response.text + assert "The YAML is valid (2 documents)." in response.text assert " Date: Sat, 21 Nov 2026 15:12:49 +0000 Subject: [PATCH 2/5] Rewrite the Compose converter and API messages for human readers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F --- .../converters/compose_to_k8s.py | 213 ++++++++++++------ services/converter-api/converters/render.py | 4 +- .../converter-api/converters/yaml_safety.py | 13 +- services/converter-api/main.py | 17 +- services/converter-api/schemas.py | 42 +++- services/converter-api/tests/test_api.py | 34 +-- .../tests/test_conversion_extras.py | 24 +- .../converter-api/tests/test_converter.py | 37 +-- services/web/messages.py | 2 +- services/web/tests/test_pages.py | 4 +- 10 files changed, 256 insertions(+), 134 deletions(-) diff --git a/services/converter-api/converters/compose_to_k8s.py b/services/converter-api/converters/compose_to_k8s.py index 4e37b63..ea5d4b5 100644 --- a/services/converter-api/converters/compose_to_k8s.py +++ b/services/converter-api/converters/compose_to_k8s.py @@ -71,7 +71,9 @@ def parse_compose(yaml_string: str) -> dict[str, Any]: ComposeError: if the YAML is invalid, not a mapping, or has no services. """ if not yaml_string or not yaml_string.strip(): - raise ComposeError("Input is empty") + raise ComposeError( + "The compose file is empty. Paste a docker-compose file with a 'services' section." + ) try: check_yaml_limits(yaml_string) @@ -86,20 +88,24 @@ def parse_compose(yaml_string: str) -> dict[str, Any]: 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 - raise ComposeError(f"Invalid YAML: {problem}", line, column) from exc + raise ComposeError(f"The YAML is invalid: {problem}.", line, column) from exc if not isinstance(data, dict): - raise ComposeError("Invalid compose file: top level must be a mapping") + raise ComposeError( + "The top level of the compose file must be a mapping of keys such as 'services'." + ) services = data.get("services") if not services: - raise ComposeError("Invalid compose file: no 'services' defined") + raise ComposeError("The compose file needs a 'services' section with at least one service.") if not isinstance(services, dict): - raise ComposeError("Invalid compose file: 'services' must be a mapping") + raise ComposeError("'services' must be a mapping of service names to their settings.") for name, config in services.items(): if config is not None and not isinstance(config, dict): - raise ComposeError(f"Invalid compose file: service '{name}' must be a mapping") + raise ComposeError( + f"Service '{name}' must be a mapping of settings such as 'image' and 'ports'." + ) return data @@ -114,7 +120,10 @@ def to_k8s_name(name: str) -> str: 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") + raise ComposeError( + f"Service name '{name}' needs at least one letter or digit to become a " + "Kubernetes name. Rename the service." + ) return cleaned @@ -123,7 +132,7 @@ def _expect_list(value: Any, field: str, service: str) -> list[Any]: if value is None: return [] if not isinstance(value, list): - raise ComposeError(f"Service '{service}': '{field}' must be a list") + raise ComposeError(f"Service '{service}': '{field}' must be a list.") return value @@ -132,7 +141,7 @@ def _expect_mapping(value: Any, field: str, service: str) -> dict[str, Any]: if value is None: return {} if not isinstance(value, dict): - raise ComposeError(f"Service '{service}': '{field}' must be a mapping") + raise ComposeError(f"Service '{service}': '{field}' must be a mapping of keys to values.") return value @@ -145,13 +154,15 @@ def parse_ports(ports: list[Any] | None) -> list[dict[str, Any]]: Returns a list of dicts: {"container_port": int, "service_port": int, "protocol": str}. """ if ports is not None and not isinstance(ports, list): - raise ComposeError("'ports' and 'expose' must be lists") + raise ComposeError("'ports' and 'expose' must each be a list.") result: list[dict[str, Any]] = [] for entry in ports or []: if isinstance(entry, dict): target = entry.get("target") if target is None: - raise ComposeError(f"Port entry {entry!r} is missing 'target'") + raise ComposeError( + f"Port entry {entry!r} needs a 'target' with the container port." + ) published = entry.get("published") or target protocol = str(entry.get("protocol", "tcp")) result.append(_port(target, published, protocol, entry)) @@ -166,7 +177,7 @@ def parse_ports(ports: list[Any] | None) -> list[dict[str, Any]]: container = parts[-1] published = parts[-2] if len(parts) >= 2 and parts[-2] else container if "-" in container or "-" in published: - raise ComposeError(f"Port ranges are not supported: '{entry}'") + raise ComposeError(f"Port entry '{entry}' is a range. List each port separately.") result.append(_port(container, published, protocol, entry)) return result @@ -177,13 +188,18 @@ def _port(container: Any, published: Any, protocol: str, raw: Any) -> dict[str, container_port = int(container) service_port = int(published) except (TypeError, ValueError) as exc: - raise ComposeError(f"Invalid port entry: '{raw}'") from exc + raise ComposeError( + f"Port entry '{raw}' is invalid. " + "Use a port such as '80' or a mapping such as '8080:80'." + ) from exc for value in (container_port, service_port): if not 1 <= value <= 65535: - raise ComposeError(f"Port out of range in entry: '{raw}'") + raise ComposeError( + f"Port entry '{raw}' is out of range. Ports must be between 1 and 65535." + ) protocol = protocol.upper() if protocol not in {"TCP", "UDP", "SCTP"}: - raise ComposeError(f"Unsupported protocol in port entry: '{raw}'") + raise ComposeError(f"Port entry '{raw}' has an unknown protocol. Use tcp, udp or sctp.") return {"container_port": container_port, "service_port": service_port, "protocol": protocol} @@ -199,15 +215,21 @@ def _environment_pairs(environment: list[Any] | dict[str, Any] | None) -> list[t elif isinstance(environment, list): for item in environment: if item is None: - raise ComposeError("'environment' list has an empty entry") + raise ComposeError( + "'environment' has an empty entry. Remove it or write it as NAME=value." + ) name, sep, value = str(item).partition("=") pairs.append((name, value if sep else None)) else: - raise ComposeError("'environment' must be a list or a mapping") + raise ComposeError( + "'environment' must be a list of NAME=value entries or a mapping of names to values." + ) for name, _ in pairs: if not name.strip(): - raise ComposeError("'environment' has a variable with an empty name") + raise ComposeError( + "'environment' has a variable with an empty name. Give every variable a name." + ) return [(name.strip(), value) for name, value in pairs] @@ -240,11 +262,15 @@ def convert_memory(value: Any) -> str: """ match = MEMORY_PATTERN.match(str(value).strip()) if not match: - raise ComposeError(f"Invalid memory value: '{value}'") + raise ComposeError( + f"Memory value '{value}' is invalid. Use a number with a unit, such as '512m' or '1g'." + ) number, unit = match.groups() unit = unit.lower() if unit not in MEMORY_UNITS and unit != "": - raise ComposeError(f"Unknown memory unit in '{value}'") + raise ComposeError( + f"Memory value '{value}' has an unknown unit. Use one of b, k, kb, m, mb, g or gb." + ) if unit in ("", "b"): # Decimal, not float: a 400-digit number would otherwise become inf and crash int(). number_bytes = int(Decimal(number)) @@ -259,15 +285,17 @@ def convert_cpus(value: Any) -> str: try: cpus = float(value) except (TypeError, ValueError) as exc: - raise ComposeError(f"Invalid cpus value: '{value}'") from exc + raise ComposeError( + f"'cpus' value '{value}' is invalid. Use a number such as '0.5' or '2'." + ) from exc if not math.isfinite(cpus): - raise ComposeError(f"Invalid cpus value: '{value}'") + raise ComposeError(f"'cpus' value '{value}' is invalid. Use a number such as '0.5' or '2'.") if cpus <= 0: - raise ComposeError(f"cpus must be greater than 0, got '{value}'") + raise ComposeError(f"'cpus' is '{value}', but it must be greater than 0.") millicores = round(cpus * 1000) if millicores < 1: # Below 1 millicore would round to a zero CPU quantity. - raise ComposeError(f"cpus must be at least 0.001, got '{value}'") + raise ComposeError(f"'cpus' is '{value}', but it must be at least 0.001.") if millicores % 1000 == 0: return str(millicores // 1000) return f"{millicores}m" @@ -291,7 +319,10 @@ def _command_list(value: Any, field: str, service: str) -> list[str]: try: return shlex.split(str(value)) except ValueError as exc: - raise ComposeError(f"Service '{service}': could not parse '{field}': {exc}") from exc + raise ComposeError( + f"Service '{service}': the quoting in '{field}' is broken ({exc}). " + f"Close every quote or write '{field}' as a list." + ) from exc def _parse_replicas(value: Any, service: str) -> int: @@ -299,10 +330,15 @@ def _parse_replicas(value: Any, service: str) -> int: text = str(value).strip() # Not str.isdigit(): that accepts '²' and other characters int() rejects. if isinstance(value, bool) or not DIGITS.fullmatch(text): - raise ComposeError(f"Service '{service}' has an invalid replicas value: '{value}'") + raise ComposeError( + f"Service '{service}': replicas must be a whole number such as 3, but it is '{value}'." + ) replicas = int(text) if replicas > MAX_REPLICAS: - raise ComposeError(f"Service '{service}' has too many replicas: {replicas}") + raise ComposeError( + f"Service '{service}': replicas is {replicas}, above the Kubernetes limit of " + f"{MAX_REPLICAS}." + ) return replicas @@ -323,17 +359,26 @@ def parse_duration(value: Any, field: str, service: str) -> int: """Compose duration ('1m30s', '500ms', '10s', or a plain number of seconds) to whole seconds, rounded up and at least 1, since Kubernetes probes take integer seconds.""" if isinstance(value, bool): - raise ComposeError(f"Service '{service}': invalid duration in '{field}': '{value}'") + raise ComposeError( + f"Service '{service}': '{field}' must be a duration such as '30s', '1m30s' or " + f"'500ms', but it is '{value}'." + ) text = str(value).strip() if re.fullmatch(r"\d+(?:\.\d+)?", text): seconds = float(text) else: 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}'") + raise ComposeError( + f"Service '{service}': '{field}' must be a duration such as '30s', '1m30s' or " + f"'500ms', but it is '{value}'." + ) 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}'") + raise ComposeError( + f"Service '{service}': '{field}' must be a duration such as '30s', '1m30s' or " + f"'500ms', but it is '{value}'." + ) return max(1, math.ceil(seconds)) @@ -375,7 +420,10 @@ def convert_healthcheck(name: str, config: dict[str, Any]) -> dict[str, Any] | N retries = check["retries"] text = str(retries).strip() if isinstance(retries, bool) or not DIGITS.fullmatch(text) or int(text) < 1: - raise ComposeError(f"Service '{name}': invalid healthcheck.retries: '{retries}'") + raise ComposeError( + f"Service '{name}': healthcheck.retries must be a whole number of 1 or more, " + f"but it is '{retries}'." + ) probe["failureThreshold"] = int(text) if check.get("start_period") is not None: probe["initialDelaySeconds"] = parse_duration( @@ -431,7 +479,10 @@ def convert_volumes( target = entry.get("target") read_only = _is_true(entry.get("read_only", False)) if not target: - raise ComposeError(f"Service '{name}': volume entry {entry!r} is missing 'target'") + raise ComposeError( + f"Service '{name}': volume entry {entry!r} needs a 'target' with the path " + "inside the container." + ) target = str(target) else: parts = str(entry).split(":") @@ -442,16 +493,21 @@ def convert_volumes( read_only = len(parts) == 3 and "ro" in parts[2].split(",") kind = "bind" if source.startswith(BIND_PREFIXES) else "volume" else: - raise ComposeError(f"Service '{name}': invalid volume entry '{entry}'") + raise ComposeError( + f"Service '{name}': volume entry '{entry}' is invalid. " + "Write it as 'source:target' or 'source:target:ro'." + ) if not target.startswith("/"): raise ComposeError( - f"Service '{name}': volume target must be an absolute path: '{target}'" + f"Service '{name}': volume target '{target}' must be an absolute path " + "that starts with '/'." ) 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 use a PersistentVolumeClaim" + f"Service '{name}': the bind mount '{source}:{target}' reads files from your " + "machine, so it was left out. Put the files in a ConfigMap or in the image. " + "You can also mount a PersistentVolumeClaim instead." ) elif kind == "tmpfs": pod.add({"name": _mount_name(target), "emptyDir": {"medium": "Memory"}}, target, False) @@ -464,8 +520,8 @@ def convert_volumes( if _is_true(spec.get("external", False)): claim = to_k8s_name(str(spec.get("name") or source)) notes.append( - f"'{name}' mounts external volume '{source}': a PersistentVolumeClaim named " - f"'{claim}' must already exist" + f"Service '{name}': volume '{source}' is external, so the manifests only " + f"mount it. Create a PersistentVolumeClaim named '{claim}' before you deploy." ) else: claims.append(claim) @@ -473,7 +529,10 @@ def convert_volumes( {"name": claim, "persistentVolumeClaim": {"claimName": claim}}, target, read_only ) else: - notes.append(f"'{name}' volume type '{kind}' is not supported and was skipped") + notes.append( + f"Service '{name}': the converter handles 'volume', 'bind' and 'tmpfs' mounts, " + f"so the '{kind}' mount was left out. Add it by hand if you need it." + ) return pod.volumes, pod.mounts, claims, notes @@ -494,20 +553,25 @@ def convert_depends_on( elif isinstance(depends, list): names = [str(d) for d in depends] else: - raise ComposeError(f"Service '{name}': 'depends_on' must be a list or a mapping") + raise ComposeError( + f"Service '{name}': 'depends_on' must be a list of service names or a mapping." + ) inits: list[dict[str, Any]] = [] notes: list[str] = [] for dep in names: if dep not in services: - raise ComposeError(f"Service '{name}' depends on unknown service '{dep}'") + raise ComposeError( + f"Service '{name}' depends on '{dep}', but the compose file has no service " + "with that name." + ) dep_name = to_k8s_name(dep) ports = _service_ports(dep, services[dep] or {}) if include_service else [] if not ports: - why = "has no ports" if include_service else "has no Service (Services were disabled)" + why = "has no ports" if include_service else "has no Service (Services are turned off)" notes.append( - f"'{name}' depends on '{dep}', which {why}: nothing to wait for, so no init " - f"container was added; make '{name}' retry its connection" + f"Service '{name}' depends on '{dep}', which {why}. Kubernetes can start " + f"'{name}' first, so make '{name}' retry its connection to '{dep}'." ) continue port = ports[0]["service_port"] @@ -538,12 +602,13 @@ def _resources(name: str, config: dict[str, Any]) -> tuple[dict[str, dict[str, s return resources, None if requests: return {"requests": requests, "limits": dict(requests)}, ( - f"'{name}' had reservations but no limits: limits set equal to the reservations" + f"Service '{name}' has reservations but no limits. The converter set the limits " + "to the reservations. Raise them if the service needs more." ) return {"requests": dict(DEFAULT_REQUESTS), "limits": dict(DEFAULT_LIMITS)}, ( - f"'{name}' had no resource limits: placeholder requests " - f"({DEFAULT_REQUESTS['cpu']}, {DEFAULT_REQUESTS['memory']}) and limits " - f"({DEFAULT_LIMITS['cpu']}, {DEFAULT_LIMITS['memory']}) were added; adjust them" + f"Service '{name}' has no resource limits, so the converter added placeholder " + f"requests ({DEFAULT_REQUESTS['cpu']}, {DEFAULT_REQUESTS['memory']}) and limits " + f"({DEFAULT_LIMITS['cpu']}, {DEFAULT_LIMITS['memory']}). Adjust them to fit the service." ) @@ -568,7 +633,10 @@ def convert_service_to_deployment( image = config.get("image") if not image: if "build" not in config: - raise ComposeError(f"Service '{name}' has neither 'image' nor 'build'") + raise ComposeError( + f"Service '{name}' needs an 'image' or a 'build' entry. " + "Add one so the converter knows which image to run." + ) # Built locally: assume the image gets tagged with the service name. image = f"{k8s_name}:latest" @@ -673,8 +741,9 @@ def convert_service_to_k8s_service( if key in seen: if seen[key] != port["container_port"]: raise ComposeError( - f"Service '{name}' publishes port {port['service_port']} twice " - f"with different container ports ({seen[key]} and {port['container_port']})" + f"Service '{name}' publishes port {port['service_port']} twice, to " + f"container ports {seen[key]} and {port['container_port']}. " + "Publish each port only once." ) continue seen[key] = port["container_port"] @@ -701,24 +770,31 @@ def _service_notes(name: str, config: dict[str, Any]) -> list[str]: notes: list[str] = [] k8s_name = to_k8s_name(name) if k8s_name != name: - notes.append(f"'{name}' was renamed to '{k8s_name}' to be a valid K8s name") + notes.append( + f"Service '{name}' was renamed to '{k8s_name}' to fit the Kubernetes naming rules." + ) if "build" in config and not config.get("image"): notes.append( - f"'{name}' uses 'build': image set to '{k8s_name}:latest'; " - "build and push it to a registry your cluster can pull from" + f"Service '{name}' builds its image, so the converter set the image to " + f"'{k8s_name}:latest'. Build and push that image to a registry your cluster can pull " + "from." ) if config.get("networks"): notes.append( - f"'{name}' uses networks: Kubernetes services reach each other by name " - "(e.g. http://db:5432), so the networks were left out" + f"Service '{name}': its networks were left out. In Kubernetes, services reach " + "each other by name, for example http://db:5432." ) if config.get("env_file"): - notes.append(f"'{name}' uses env_file: move those values into a ConfigMap or Secret") + notes.append( + f"Service '{name}' reads variables from env_file, which was left out. " + "Move those values into a ConfigMap or a Secret." + ) for var_name, value in _environment_pairs(config.get("environment")): if value is None: notes.append( - f"'{name}' env var '{var_name}' has no value " - "(compose reads it from the host); set it or use a Secret" + f"Service '{name}': variable '{var_name}' gets its value from the host in " + "compose, so the manifest sets it to an empty string. " + "Set a value or load it from a Secret." ) return notes @@ -739,10 +815,12 @@ def convert_compose_to_k8s( """ services = compose_dict.get("services") if isinstance(compose_dict, dict) else None if not services or not isinstance(services, dict): - raise ComposeError("Invalid compose file: no 'services' defined") + raise ComposeError("The compose file needs a 'services' section with at least one service.") declared_volumes = compose_dict.get("volumes") or {} if not isinstance(declared_volumes, dict): - raise ComposeError("Invalid compose file: top-level 'volumes' must be a mapping") + raise ComposeError( + "The top-level 'volumes' section must be a mapping of volume names to their settings." + ) services = {str(name): (config or {}) for name, config in services.items()} deployments: list[dict[str, Any]] = [] @@ -755,7 +833,8 @@ def convert_compose_to_k8s( k8s_name = to_k8s_name(name) if k8s_name in used_names: raise ComposeError( - f"Services '{used_names[k8s_name]}' and '{name}' both map to K8s name '{k8s_name}'" + f"Services '{used_names[k8s_name]}' and '{name}' would both get the " + f"Kubernetes name '{k8s_name}'. Rename one of them." ) used_names[k8s_name] = name @@ -779,13 +858,15 @@ def convert_compose_to_k8s( for claim, users in claim_users.items(): shared = f", shared by {', '.join(repr(u) for u in users)}" if len(users) > 1 else "" notes.append( - f"volume '{claim}' became a PersistentVolumeClaim of {DEFAULT_VOLUME_SIZE} " - f"(placeholder size, ReadWriteOnce{shared}); adjust it before applying" + f"Volume '{claim}' is a ReadWriteOnce PersistentVolumeClaim of " + f"{DEFAULT_VOLUME_SIZE}{shared}. The size is a placeholder, so set the real size " + "before you deploy." ) 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 cannot" + f"Volume '{claim}' is mounted by more than one service. With ReadWriteOnce, " + "their pods must run on the same node. Use ReadWriteMany storage if they need " + "to run on different nodes." ) namespaces = [] if namespace == "default" else [namespace_manifest(namespace)] diff --git a/services/converter-api/converters/render.py b/services/converter-api/converters/render.py index d9ef20d..d42fa8b 100644 --- a/services/converter-api/converters/render.py +++ b/services/converter-api/converters/render.py @@ -31,7 +31,7 @@ def render_files( output="helm": a chart with Chart.yaml, values.yaml and one template per resource. """ if output not in OUTPUTS: - raise ComposeError(f"Unknown output '{output}'. Use one of: {', '.join(OUTPUTS)}") + raise ComposeError(f"Output '{output}' is unknown. Use one of: {', '.join(OUTPUTS)}.") manifests = result["manifests"] if output == "manifests": return [ @@ -147,7 +147,7 @@ def render(self) -> list[dict[str, str]]: chart = { "apiVersion": "v2", "name": self.chart_name, - "description": "Generated by DevToolkit from a docker-compose file", + "description": "A Helm chart converted from a docker-compose file by DevToolkit", "type": "application", "version": "0.1.0", "appVersion": "0.1.0", diff --git a/services/converter-api/converters/yaml_safety.py b/services/converter-api/converters/yaml_safety.py index e6569df..23c74c1 100644 --- a/services/converter-api/converters/yaml_safety.py +++ b/services/converter-api/converters/yaml_safety.py @@ -124,11 +124,17 @@ def check_yaml_limits(text: str, max_depth: int = MAX_DEPTH, max_nodes: int = MA if isinstance(event, yaml.NodeEvent): nodes += 1 if nodes > max_nodes: - raise YamlLimitError(f"Input too large: more than {max_nodes} values") + raise YamlLimitError( + f"The YAML is too large: it has more than {max_nodes:,} values. " + "Make it smaller and try again." + ) if isinstance(event, yaml.CollectionStartEvent): depth += 1 if depth > max_depth: - raise YamlLimitError("Invalid YAML: nested too deeply") + raise YamlLimitError( + f"The YAML is nested too deeply. Use at most {max_depth} levels of lists " + "and mappings." + ) elif isinstance(event, yaml.CollectionEndEvent): depth -= 1 @@ -145,7 +151,8 @@ def check_node_count(data: Any, limit: int = MAX_NODES) -> None: count += 1 if count > limit: raise YamlLimitError( - f"Input too large: more than {limit} values after expanding YAML aliases" + f"The YAML is too large: it has more than {limit:,} values once its aliases " + "are expanded. Use fewer aliases or a smaller file." ) if isinstance(node, dict): stack.extend(node.keys()) diff --git a/services/converter-api/main.py b/services/converter-api/main.py index c31309c..fc1c02f 100644 --- a/services/converter-api/main.py +++ b/services/converter-api/main.py @@ -32,7 +32,10 @@ def resolve_log_level(value: str | None) -> tuple[str, str | None]: 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}" + return ( + "INFO", + f"LOG_LEVEL {value!r} is unknown, so the service logs at info. Use one of: {allowed}.", + ) logger = logging.getLogger("converter-api") @@ -50,10 +53,10 @@ def configure_logging(value: str | None) -> str: LOG_LEVEL = configure_logging(os.getenv("LOG_LEVEL")) app = FastAPI( - title="DevToolkit converter-api", + title="DevToolkit converter API", description=( - "Convert docker-compose files into Kubernetes manifests and CloudFormation, AWS SAM " - "and AWS CDK templates into Terraform." + "Converts docker-compose files to Kubernetes manifests or a Helm chart. " + "Converts CloudFormation, AWS SAM and AWS CDK templates to Terraform." ), version="1.0.0", ) @@ -148,8 +151,8 @@ def convert_cfn(request: CfnRequest) -> dict[str, Any] | 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.", + "error": "The converter failed on an unexpected structure in this template. " + "Open an issue with a small example template so it can be fixed.", }, ) response: dict[str, Any] = {"success": True} @@ -170,7 +173,7 @@ def validate_yaml(request: ValidateRequest) -> dict[str, Any]: # Only the parser's description of the input is returned, never the exception text. problem = getattr(exc, "problem", None) or "syntax error" mark = getattr(exc, "problem_mark", None) - response: dict[str, Any] = {"valid": False, "error": f"Invalid YAML: {problem}"} + response: dict[str, Any] = {"valid": False, "error": f"The YAML is invalid: {problem}."} if mark is not None: response["line"] = mark.line + 1 response["column"] = mark.column + 1 diff --git a/services/converter-api/schemas.py b/services/converter-api/schemas.py index e6a925e..4bae51b 100644 --- a/services/converter-api/schemas.py +++ b/services/converter-api/schemas.py @@ -19,16 +19,26 @@ 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 + compose_yaml: str = Field( + ..., max_length=MAX_INPUT_CHARS, description="The docker-compose file to convert, as YAML." + ) + namespace: str = Field( + "default", + pattern=NAMESPACE_PATTERN, + description="Kubernetes namespace of the resources. Any namespace other than 'default' " + "also gets a Namespace manifest.", + ) + include_service: bool = Field( + True, description="Add a ClusterIP Service for each compose service that has ports." + ) 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." + "manifests", + description="'manifests' returns one YAML file per resource. 'helm' returns a Helm chart.", ) @@ -38,27 +48,37 @@ class CfnRequest(BaseModel): template: str = Field( ..., max_length=MAX_TEMPLATE_CHARS, - description="CloudFormation, AWS SAM or `cdk synth` template, JSON or YAML", + description="The CloudFormation, AWS SAM or `cdk synth` template to convert, as 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.", + description="'aws' uses the aws provider for every type the converter maps by hand " + "and awscc for the rest. 'awscc' uses the awscc provider for every resource.", ) layout: Literal["files", "single"] = Field( - "files", description="'files': versions.tf, variables.tf, main.tf... 'single': main.tf" + "files", + description="'files' splits the output into versions.tf, variables.tf, main.tf and more " + "files. 'single' puts everything in main.tf.", ) stack_name: str | None = Field( None, pattern=STACK_NAME_PATTERN, - description="Default for var.stack_name, which replaces AWS::StackName", + description="Default value of var.stack_name. The Terraform code uses it wherever the " + "template uses AWS::StackName.", ) include_imports: bool = Field( - False, description="Also write imports.tf, to adopt resources the stack already created" + False, + description="Also write imports.tf, so Terraform can take over the 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) + yaml: str = Field( + ..., + max_length=MAX_INPUT_CHARS, + description="The YAML to check. Separate several documents with ---.", + ) diff --git a/services/converter-api/tests/test_api.py b/services/converter-api/tests/test_api.py index 580365b..c85ec9d 100644 --- a/services/converter-api/tests/test_api.py +++ b/services/converter-api/tests/test_api.py @@ -40,7 +40,10 @@ def test_convert_json(): assert body["success"] is True assert body["manifests"]["deployments"][0]["metadata"]["name"] == "web" assert body["manifests"]["services"][0]["spec"]["ports"][0]["port"] == 80 - assert any(n.startswith("'web' had no resource limits: placeholder") for n in body["notes"]) + assert any( + n.startswith("Service 'web' has no resource limits, so the converter added placeholder") + for n in body["notes"] + ) def test_convert_yaml(): @@ -58,7 +61,7 @@ def test_convert_invalid_yaml(): assert response.status_code == 400 body = response.json() assert body["success"] is False - assert body["error"].startswith("Invalid YAML") + assert body["error"].startswith("The YAML is invalid") def test_convert_rejects_bad_namespace(): @@ -84,7 +87,7 @@ def test_validate_yaml_invalid(): response = client.post("/validate/yaml", json={"yaml": "a: 1\n b: 2\n"}) body = response.json() assert body["valid"] is False - assert body["error"].startswith("Invalid YAML") + assert body["error"].startswith("The YAML is invalid") assert body["line"] == 2 @@ -94,7 +97,10 @@ def test_deep_nesting_is_not_a_server_error(): assert response.status_code == 400 response = client.post("/validate/yaml", json={"yaml": deep}) assert response.status_code == 200 - assert response.json() == {"valid": False, "error": "Invalid YAML: nested too deeply"} + assert response.json() == { + "valid": False, + "error": "The YAML is nested too deeply. Use at most 100 levels of lists and mappings.", + } def test_validate_yaml_block_nesting(): @@ -114,7 +120,7 @@ def test_validate_yaml_merge_key_bomb_is_fast(): def test_validate_yaml_too_many_values(): response = client.post("/validate/yaml", json={"yaml": "[" + ",".join(["a"] * 20000) + "]"}) - assert response.json()["error"].startswith("Input too large") + assert response.json()["error"].startswith("The YAML is too large") @pytest.mark.parametrize( @@ -128,7 +134,7 @@ def test_resolve_log_level_valid(value, expected): def test_resolve_log_level_unknown_falls_back_to_info(): level, warning = resolve_log_level("verbose") assert level == "INFO" - assert "Unknown LOG_LEVEL 'verbose'" in warning + assert "LOG_LEVEL 'verbose' is unknown" in warning assert "debug, info, warning, error, critical" in warning @@ -144,13 +150,13 @@ def test_unknown_log_level_does_not_crash_startup(): text=True, ) assert result.returncode == 0, result.stderr - assert "Unknown LOG_LEVEL 'verbose'" in result.stderr + assert "LOG_LEVEL 'verbose' is unknown" in result.stderr def test_configure_logging_warns_on_unknown_level(caplog): with caplog.at_level(logging.WARNING, logger="converter-api"): assert configure_logging("loud") == "INFO" - assert "Unknown LOG_LEVEL 'loud'" in caplog.text + assert "LOG_LEVEL 'loud' is unknown" in caplog.text def test_validate_yaml_rejects_python_tags(): @@ -160,7 +166,7 @@ def test_validate_yaml_rejects_python_tags(): assert response.status_code == 200 body = response.json() assert body["valid"] is False - assert body["error"].startswith("Invalid YAML: could not determine a constructor") + assert body["error"].startswith("The YAML is invalid: could not determine a constructor") def test_convert_rejects_python_tags(): @@ -169,7 +175,7 @@ def test_convert_rejects_python_tags(): json={"compose_yaml": "services: !!python/object/apply:os.system ['echo pwned']"}, ) assert response.status_code == 400 - assert response.json()["error"].startswith("Invalid YAML") + assert response.json()["error"].startswith("The YAML is invalid") def test_convert_files_manifests(): @@ -213,7 +219,7 @@ def test_convert_files_rejects_unknown_output_and_bad_compose(): assert response.status_code == 400 assert response.json() == { "success": False, - "error": "Invalid compose file: no 'services' defined", + "error": "The compose file needs a 'services' section with at least one service.", } @@ -225,7 +231,7 @@ def test_convert_error_carries_line_and_column_for_yaml_syntax_errors(): assert response.status_code == 400 body = response.json() assert body["success"] is False - assert body["error"].startswith("Invalid YAML") + assert body["error"].startswith("The YAML is invalid") assert body["line"] >= 1 and body["column"] >= 1 # Other errors have no position. response = client.post("/convert/compose-to-k8s/files", json={"compose_yaml": "services: {}"}) @@ -283,7 +289,7 @@ 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["success"] is False and body["error"] assert body["line"] == 2 @@ -309,5 +315,5 @@ def test_cfn_to_terraform_unexpected_shape_is_a_400(monkeypatch, caplog): 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 structure in this template" in response.json()["error"] assert "unexpected template shape" in caplog.text diff --git a/services/converter-api/tests/test_conversion_extras.py b/services/converter-api/tests/test_conversion_extras.py index ee9f95f..eaaa8b0 100644 --- a/services/converter-api/tests/test_conversion_extras.py +++ b/services/converter-api/tests/test_conversion_extras.py @@ -48,7 +48,7 @@ def test_parse_duration(value, seconds): @pytest.mark.parametrize("value", ["", "soon", "10x", "-5s", True, 0, "inf"]) def test_parse_duration_invalid(value): - with pytest.raises(ComposeError, match="invalid duration"): + with pytest.raises(ComposeError, match="must be a duration"): parse_duration(value, "interval", "web") @@ -130,7 +130,7 @@ def test_named_volume_becomes_pvc_and_mount(): assert pvcs[0]["kind"] == "PersistentVolumeClaim" assert pvcs[0]["metadata"] == {"name": "dbdata", "namespace": "default"} assert pvcs[0]["spec"]["resources"]["requests"]["storage"] == DEFAULT_VOLUME_SIZE - assert any("placeholder size" in n for n in result["notes"]) + assert any("The size is a placeholder" in n for n in result["notes"]) def test_shared_named_volume_is_one_pvc_with_a_warning(): @@ -187,17 +187,17 @@ def test_long_syntax_volume_and_external_volume(): assert [p["metadata"]["name"] for p in result["manifests"]["persistent_volume_claims"]] == [ "media" ] - assert any("must already exist" in n for n in result["notes"]) + assert any("Create a PersistentVolumeClaim named" in n for n in result["notes"]) def test_volume_errors(): - with pytest.raises(ComposeError, match="missing 'target'"): + with pytest.raises(ComposeError, match="needs a 'target'"): convert_volumes("web", {"volumes": [{"type": "volume", "source": "x"}]}, {}) - with pytest.raises(ComposeError, match="invalid volume entry"): + with pytest.raises(ComposeError, match="volume entry 'a:b:c:d' is invalid"): convert_volumes("web", {"volumes": ["a:b:c:d"]}, {}) with pytest.raises(ComposeError, match="absolute path"): convert_volumes("web", {"volumes": ["data:relative/path"]}, {}) - with pytest.raises(ComposeError, match="top-level 'volumes' must be a mapping"): + with pytest.raises(ComposeError, match="top-level 'volumes' section must be a mapping"): convert("services:\n web:\n image: x\nvolumes: [a, b]\n") @@ -206,7 +206,7 @@ def test_unsupported_volume_type_is_skipped_with_note(): "web", {"volumes": [{"type": "npipe", "source": "x", "target": "/x"}]}, {} ) assert volumes == [] and mounts == [] and claims == [] - assert "not supported" in notes[0] + assert "was left out" in notes[0] # --- depends_on -> init containers ------------------------------------------------------- @@ -254,13 +254,13 @@ def test_depends_on_without_services_is_a_note(): include_service=False, ) assert "initContainers" not in container_of(result) - assert any("Services were disabled" in n for n in result["notes"]) + assert any("Services are turned off" in n for n in result["notes"]) def test_depends_on_errors(): - with pytest.raises(ComposeError, match="unknown service 'db'"): + with pytest.raises(ComposeError, match="has no service with that name"): convert("services:\n web:\n image: x\n depends_on: [db]\n") - with pytest.raises(ComposeError, match="must be a list or a mapping"): + with pytest.raises(ComposeError, match="must be a list of service names or a mapping"): convert_depends_on("web", {"depends_on": "db"}, {"db": {}}, True) @@ -283,7 +283,7 @@ def test_reservations_without_limits_become_guaranteed(): ) resources = container_of(result)["containers"][0]["resources"] assert resources["requests"] == resources["limits"] == {"cpu": "250m", "memory": "64Mi"} - assert any("limits set equal to the reservations" in n for n in result["notes"]) + assert any("set the limits to the reservations" in n for n in result["notes"]) LIMITS_ONLY = ( @@ -390,7 +390,7 @@ def test_render_helm_without_resources_block(): def test_render_unknown_output(): - with pytest.raises(ComposeError, match="Unknown output"): + with pytest.raises(ComposeError, match="Output 'kustomize' is unknown"): render_files(convert("services:\n web:\n image: x\n"), "kustomize") diff --git a/services/converter-api/tests/test_converter.py b/services/converter-api/tests/test_converter.py index 3703395..59d6c52 100644 --- a/services/converter-api/tests/test_converter.py +++ b/services/converter-api/tests/test_converter.py @@ -272,11 +272,11 @@ def test_command_and_entrypoint(): def test_build_uses_service_name_as_image(): result = convert_compose_to_k8s({"services": {"api": {"build": "."}}}) assert container_of(result["manifests"]["deployments"][0])["image"] == "api:latest" - assert any("uses 'build'" in note for note in result["notes"]) + assert any("builds its image" in note for note in result["notes"]) def test_service_without_image_or_build(): - with pytest.raises(ComposeError, match="neither 'image' nor 'build'"): + with pytest.raises(ComposeError, match="needs an 'image' or a 'build'"): convert_service_to_deployment("x", {}) @@ -287,7 +287,7 @@ def test_name_sanitising(): def test_name_collision(): - with pytest.raises(ComposeError, match="both map"): + with pytest.raises(ComposeError, match="would both get the Kubernetes name"): convert_compose_to_k8s({"services": {"my_app": {"image": "a"}, "my-app": {"image": "b"}}}) @@ -315,7 +315,7 @@ def test_notes_for_manual_attention(): notes = " | ".join(convert_compose_to_k8s(compose)["notes"]) for expected in [ "renamed to 'web-app'", - "bind mount './data:/data' was not converted", + "bind mount './data:/data' reads files from your machine", "reach each other by name", "env_file", "placeholder requests", @@ -330,7 +330,7 @@ def test_notes_for_manual_attention(): def test_invalid_yaml_handling(): - with pytest.raises(ComposeError, match="Invalid YAML"): + with pytest.raises(ComposeError, match="The YAML is invalid"): parse_compose("services:\n web:\n image: nginx\n ports: [80") @@ -349,7 +349,7 @@ def test_empty_input(text): ], ) def test_missing_services_error(text): - with pytest.raises(ComposeError, match="no 'services'"): + with pytest.raises(ComposeError, match="needs a 'services' section"): parse_compose(text) @@ -359,12 +359,12 @@ def test_top_level_must_be_mapping(): def test_services_must_be_mapping(): - with pytest.raises(ComposeError, match="'services' must be a mapping"): + with pytest.raises(ComposeError, match="'services' must be a mapping of service names"): parse_compose("services:\n - web\n") def test_service_must_be_mapping(): - with pytest.raises(ComposeError, match="service 'web' must be a mapping"): + with pytest.raises(ComposeError, match="Service 'web' must be a mapping"): parse_compose("services:\n web: nginx\n") @@ -393,7 +393,7 @@ def _alias_bomb(levels: int) -> str: def test_alias_bomb_rejected_quickly(): - with pytest.raises(ComposeError, match="Input too large"): + with pytest.raises(ComposeError, match="The YAML is too large"): parse_compose(_alias_bomb(8)) @@ -466,13 +466,13 @@ def test_wrong_field_types_give_clear_errors(snippet, message): def test_parse_ports_rejects_non_list(): - with pytest.raises(ComposeError, match="must be lists"): + with pytest.raises(ComposeError, match="must each be a list"): parse_ports("8080:80") def test_unbalanced_quotes_in_command(): compose = parse_compose('services:\n w:\n image: x\n command: "echo \'hi"\n') - with pytest.raises(ComposeError, match="could not parse 'command'"): + with pytest.raises(ComposeError, match="the quoting in 'command' is broken"): convert_compose_to_k8s(compose) @@ -542,7 +542,7 @@ def test_merge_keys_last_value_wins(): def test_too_many_values_rejected_before_loading(): flat = "services:\n w:\n image: x\n labels: [" + ",".join(["a"] * 30000) + "]\n" start = time.perf_counter() - with pytest.raises(ComposeError, match="Input too large"): + with pytest.raises(ComposeError, match="The YAML is too large"): parse_compose(flat) assert time.perf_counter() - start < 0.5 @@ -570,14 +570,14 @@ def test_explicit_empty_env_value_not_flagged_as_host_var(): "services:\n w:\n image: x\n environment: ['EMPTY=', 'FROM_HOST']\n" ) notes = " | ".join(convert_compose_to_k8s(compose)["notes"]) - assert "'FROM_HOST' has no value" in notes + assert "variable 'FROM_HOST' gets its value from the host" in notes assert "EMPTY" not in notes def test_dict_env_null_vs_empty_string(): compose = parse_compose("services:\n w:\n image: x\n environment: {A: , B: ''}\n") notes = " | ".join(convert_compose_to_k8s(compose)["notes"]) - assert "'A' has no value" in notes + assert "variable 'A' gets its value from the host" in notes assert "'B'" not in notes @@ -587,7 +587,10 @@ def test_placeholder_resources_when_no_k8s_limits_generated(): "services:\n w:\n image: x\n deploy: {resources: {limits: {pids: 5}}}\n" ) result = convert_compose_to_k8s(compose) - assert any(n.startswith("'w' had no resource limits: placeholder") for n in result["notes"]) + assert any( + n.startswith("Service 'w' has no resource limits, so the converter added placeholder") + for n in result["notes"] + ) container = result["manifests"]["deployments"][0]["spec"]["template"]["spec"]["containers"][0] assert container["resources"]["limits"] == {"cpu": "500m", "memory": "512Mi"} @@ -603,7 +606,9 @@ def test_invalid_env_entries_rejected(environment, message): def test_python_object_tags_are_rejected(): """The loaders are SafeLoader subclasses: YAML can never build Python objects.""" - with pytest.raises(ComposeError, match="Invalid YAML: could not determine a constructor"): + with pytest.raises( + ComposeError, match="The YAML is invalid: could not determine a constructor" + ): parse_compose("services: !!python/object/apply:os.system ['echo pwned']") diff --git a/services/web/messages.py b/services/web/messages.py index 71b8eb4..e4e0384 100644 --- a/services/web/messages.py +++ b/services/web/messages.py @@ -34,7 +34,7 @@ LENGTH_REQUIRED = "Content-Length required" TOO_LARGE = "The request is too large" -UNKNOWN_LOG_LEVEL = 'Unknown LOG_LEVEL "{value}": using info. Allowed: {allowed}' +UNKNOWN_LOG_LEVEL = 'LOG_LEVEL "{value}" is unknown, so the service logs at info. Use one of: {allowed}.' NOTES_TITLE = "# Conversion notes" NOTES_INTRO = ( diff --git a/services/web/tests/test_pages.py b/services/web/tests/test_pages.py index 472d54f..854d8d6 100644 --- a/services/web/tests/test_pages.py +++ b/services/web/tests/test_pages.py @@ -505,14 +505,14 @@ def test_resolve_log_level(): assert resolve_log_level(" Debug ") == ("DEBUG", None) level, warning = resolve_log_level("loud") assert level == "INFO" - assert 'Unknown LOG_LEVEL "loud": using info.' in warning + assert 'LOG_LEVEL "loud" is unknown, so the service logs at info.' in warning def test_configure_logging_warns_on_unknown_level(caplog): assert configure_logging("warning") == "WARNING" with caplog.at_level("WARNING", logger="web"): assert configure_logging("loud") == "INFO" - assert 'Unknown LOG_LEVEL "loud"' in caplog.text + assert 'LOG_LEVEL "loud" is unknown' in caplog.text def test_other_http_errors_render_the_error_page(fake_api): From a3e92cd57edd6cc947a1aa0ad19d67e4783a4d90 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:13:13 +0000 Subject: [PATCH 3/5] Rewrite the docs for human readers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F --- .github/ISSUE_TEMPLATE/bug_report.yml | 8 +- .github/ISSUE_TEMPLATE/config.yml | 2 +- .github/ISSUE_TEMPLATE/feature_request.yml | 6 +- .github/pull_request_template.md | 10 +-- CONTRIBUTING.md | 82 ++++++++++--------- README.md | 48 +++++------ SECURITY.md | 14 ++-- docs/README.md | 20 ++--- docs/architecture.md | 27 ++++-- docs/configuration.md | 14 ++-- docs/operations/ci-cd.md | 30 +++---- docs/operations/deploy.md | 18 ++-- docs/reference/api.md | 50 +++++------ docs/reference/cloudformation-to-terraform.md | 58 ++++++------- docs/reference/conversion-rules.md | 42 +++++----- docs/roadmap.md | 20 ++--- 16 files changed, 235 insertions(+), 214 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index e831d63..f44f512 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,23 +1,23 @@ name: Bug report -description: Something converts wrongly, crashes or doesn't work as documented +description: Something converts wrongly, crashes or works differently from the docs labels: [bug] body: - type: markdown attributes: value: | - Found a security problem? Please **don't** file it here. See [SECURITY.md](https://github.com/zainsohail88/devtoolkit/blob/main/SECURITY.md). + Found a security problem? Please report it privately as described in [SECURITY.md](https://github.com/zainsohail88/devtoolkit/blob/main/SECURITY.md). - type: textarea id: what-happened attributes: label: What happened? - description: What did you expect, and what did you get instead? + description: What did you expect and what did you get instead? validations: required: true - type: textarea id: input attributes: label: Input - description: The compose file or request body that shows the problem. Remove anything private first. + description: The compose file, template or request body that shows the problem. Remove anything private first. render: yaml validations: required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 697ab66..e10670d 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -2,4 +2,4 @@ blank_issues_enabled: false contact_links: - name: Report a security vulnerability url: https://github.com/zainsohail88/devtoolkit/security/advisories/new - about: Please report security problems privately, not as a public issue. + about: Report security problems privately through a GitHub security advisory. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index 0578cac..fb24ad6 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -6,17 +6,17 @@ body: id: problem attributes: label: What problem would this solve? - description: Describe the task you're trying to do today and what makes it hard. + description: Describe the task you are trying to do today and what makes it hard. validations: required: true - type: textarea id: proposal attributes: label: What would you like? - description: For a conversion rule, show an example input and the output you'd expect. + description: For a conversion rule, show an example input and the output you would expect. validations: required: true - type: textarea id: alternatives attributes: - label: Alternatives you've considered + label: Alternatives you have considered diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index d0ecdf8..06b6573 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,15 +1,15 @@ ## What and why - + ## How it was tested - + ## Checklist - [ ] `make lint test` passes (coverage stays at or above 95%) - [ ] `make validate-k8s` passes, if anything in `k8s/` changed -- [ ] New behaviour has tests, including error cases -- [ ] README / CONTRIBUTING updated, if endpoints or conversion rules changed -- [ ] No secrets, tokens or personal data added +- [ ] New behaviour has tests, including the error cases +- [ ] The docs are updated, if endpoints or conversion rules changed +- [ ] The change adds no secrets, tokens or personal data diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9555706..4fb38a1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to DevToolkit -Thanks for helping. This guide covers local setup, the code rules, adding a converter or service and the PR process. +Thanks for helping. This guide covers local setup, the code rules, how to add a converter or a service and the pull request process. ## Local setup @@ -18,61 +18,67 @@ Install [kubeconform](https://github.com/yannh/kubeconform) if you change anythi `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). +- **Define functions at module or class level.** A function or method never defines another one. Write a named function where you would use a lambda. To pass a callback, pass a bound method. +- **Write arguments out in full.** The checker rejects star imports, `*args`, `**kwargs`, keyword-only markers and unpacking. Write `a + [b]`, `dict(a, key=value)` and explicit arguments instead. +- **Put imports at the top of the module**, before any other statement. Keep them out of functions, classes, `if` blocks and tests. +- **Fix problems at the cause.** The checker rejects comments that switch a checker off, such as `noqa`, `type: ignore`, `pragma: no cover` and `nosec`. +- **Give each class one job.** Put dataclasses in a `models.py` and constants in a `constants.py`. An `__init__.py` holds only a docstring or plain imports. +- **Add docstrings and type hints** to every module, class, function and method outside `tests/`. The docstring says what the code does and gives an example when the input format needs one. +- **Use comments to explain why**, in plain words. +- **Let ruff format the code.** `make format` fixes most formatting problems. ## Writing rules -For the docs, page copy and every message a user reads (errors, conversion notes): +These rules apply to the docs, the page copy and every message a user reads, such as errors and 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. +- Say what something does or is. Leave out what goes without saying. +- Write without apostrophes: "does not" and "the stack name". +- Put no comma before "and" or "or". +- Use a full stop or a colon where you would use an em dash. -The Markdown checks run with the code rules. +`scripts/check_code_rules.py` checks the last three rules in `README.md`, `CONTRIBUTING.md`, `SECURITY.md` and `docs/`. ## Adding a new 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`. +1. **Logic.** Create a package `services/converter-api/converters/k8s_to_compose/`. Its classes and functions take strings or dicts and return dicts. Keep FastAPI imports out of it, so the logic stays easy to test. Give it a `models.py`, a `constants.py` and an `errors.py` with an error class whose message is safe to show the user. +2. **Endpoint.** Add a route in `services/converter-api/main.py` with a Pydantic request model. Set a `max_length` on its text fields. Return `{"success": true, ...}` on success and HTTP 400 with `{"success": false, "error": "..."}` for bad input. +3. **Tests.** Cover the happy path, each supported input format and every error branch. CI fails below 95% coverage. The current code is at 100%, so please keep it there. +4. **Page.** Add a template in `services/web/templates/` and a router in `services/web/routes/`, following `routes/compose.py`. Put the form dataclass in `models.py`, its checks in `inputs.py`, the converter-api call in `conversions.py` and every text the user reads in `messages.py`. Include the router in `main.py` and link the page 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 -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. +Each CloudFormation type with a hand-written `aws` provider mapping is a subclass of `ResourceConverter` (`converters/cfn/resources/base.py`). The subclass lives in one of the modules in `converters/cfn/resources/` and is listed in the `CONVERTERS` tuple of that module. + +- The class names the CloudFormation type, the Terraform type and the attributes that `Ref` and `Fn::GetAtt` read. +- Its `convert(b)` method takes properties one at a time from `b.props` (`attr`, `number`, `json`, `tags`, `block`...). Any property it leaves in `b.props` is kept as a comment and reported in the notes. +- Check attribute names against the provider schema (`terraform providers schema -json`). Then 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`. When you bump the awscc version, rebuild that file with `python -m tools.build_awscc_index` from `services/converter-api`. ## 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. +1. Create `services//` with a `Dockerfile` that follows the existing ones: multi-stage, non-root UID 10001, a `HEALTHCHECK` and `/health` and `/ready` endpoints. +2. Add manifests in `k8s//` that follow the `web` pattern: probes, resource limits, a non-root security context and a ConfigMap for its settings. Put the image name in `deployment.yaml`. The 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 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. +The design system is one file: `services/web/styles/input.css`. Every colour, size, radius and font is a token there. Each token is named for its job (`surface`, `ink`, `accent`) and has its light and dark values side by side. -- **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` (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. +- **Use token classes in templates.** Use the 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`). `input.css` removes the Tailwind palette, radii and text sizes, so classes such as `bg-slate-50` or `rounded-lg` produce no CSS. When you need a value the tokens lack, add a token. +- **Build one component per concept.** A variant is a modifier class (`btn-primary`). A part that two pages share, such as the file list with tabs, is one template that both include (`_files.html`). +- **Support both themes.** Give each new colour a light and a dark value and check the contrast: 4.5:1 for text and 3:1 for interface borders. Keep the two dark blocks in `input.css` identical. +- **Respect keyboard and motion settings.** Anything clickable is at least 44px tall (`min-h-11`) and focus stays visible. Animation follows `prefers-reduced-motion`, which `input.css` handles for every page. +- **Keep scripts to two files.** `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 sets the theme before first paint. The Content-Security-Policy allows it by hash, so keep it the only inline script. +- **Inline icons.** Icons are inline SVGs from `templates/icons/` (`{% include "icons/copy.svg" %}`), sized by the `.icon` class. Take new icons from the pinned Lucide release named in the docs, strip `width`/`height` and add `aria-hidden="true"`. +- **Use the shared editor.** YAML and Terraform go through the CodeMirror editor in `services/web/editor/`, which reads its colours from the tokens. A new tool page needs a `[data-editor]` container around its textarea and a result fragment. `app.js` does the rest. +- **Follow the writing rules.** See the writing rules above. The product is called DevToolkit and each page names what its 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. +`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. ## Kubernetes manifest rules @@ -84,16 +90,16 @@ Every container must have: The `devtoolkit` namespace enforces the `restricted` Pod Security Standard, so the cluster rejects pods that break these rules. -**Secrets stay outside code and manifests.** Use GitHub repo variables, Workload Identity or Kubernetes Secrets created outside the repo. +**Keep secrets out of code and manifests.** Use GitHub repo variables, Workload Identity or Kubernetes Secrets that you create outside the repo. ## Pull request process 1. Branch from `main`. -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, 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. +2. Keep each PR to one change, such as one converter or one fix. +3. Before you push, run `make lint test`. If you changed `k8s/`, run `make validate-k8s` too. +4. Open a PR into `main`. CI must pass: lint, tests, Docker builds, manifest validation, Terraform validation and the end-to-end test on kind. +5. A maintainer reviews and merges it. A merge to `main` builds and pushes the images of the services that changed. ## License -By contributing, you agree your contributions are licensed under the [MIT License](LICENSE). +By contributing, you agree that your contributions are licensed under the [MIT License](LICENSE). diff --git a/README.md b/README.md index 947ca64..c88abb3 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,17 @@ # DevToolkit -Practical DevOps conversion tools, built as microservices on Kubernetes. +DevToolkit converts infrastructure code from one tool to another. It runs as two small services on Kubernetes. -**Try it:** [devtoolkit.cloud.run](https://devtoolkit.cloud.run) +**Hosted version:** [devtoolkit.cloud.run](https://devtoolkit.cloud.run) -DevToolkit has two jobs: +DevToolkit has two converters. Each one has a web page and an API endpoint: -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. +- Docker Compose to Kubernetes +- CloudFormation, AWS SAM and AWS CDK to Terraform -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. +The project also shows how to run a small service on Kubernetes. It uses plain manifests, health probes, resource limits, non-root containers, a NetworkPolicy and a full CI/CD pipeline. All of it is small enough to read in one sitting. + +The **web** service serves the pages and **converter-api** does the conversions. Only web can call the API. ## Quick start @@ -19,17 +21,17 @@ It is two services: **web** serves the pages you use in a browser and **converte |------|-----------------|------------| | [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 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) | +| [curl](https://curl.se/) | Any current release | Dev Mode: downloads the Tailwind CLI once to build the web UI stylesheet | +| [Node.js](https://nodejs.org/) | 22 | Dev Mode: `make editor` bundles the code editor of the web UI once | +| [Docker](https://docs.docker.com/get-docker/) | Any current release | Kubernetes Mode: builds the images and runs kind | | [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 | +| [kubectl](https://kubernetes.io/docs/tasks/tools/) | 1.36 (the cluster runs Kubernetes 1.37) | Kubernetes Mode | +| [jq](https://jqlang.org/) | 1.5 | The [example](#example) below | +| [Terraform](https://developer.hashicorp.com/terraform/install) | 1.5 | `make validate-terraform`, which checks the Terraform that the CloudFormation converter writes | #### Dev Mode -Runs both services directly with Python and reloads on every code change. +Dev Mode runs both services with Python and reloads them when you change the code. ```bash make install # create .venv and install dependencies for every service @@ -40,7 +42,7 @@ make run-web # in a second terminal: start the web UI on http:// #### Kubernetes Mode -Builds both images and runs them on a local kind cluster, using the same manifests as production. +Kubernetes Mode builds both images and runs them on a local kind cluster with the same manifests as production. ```bash make deploy-local # create the kind cluster if needed, build the images, deploy k8s/ @@ -57,7 +59,7 @@ make help # list every make target with a short description ## Example -Send a Docker Compose file and get back Kubernetes Deployments and Services, plus notes on anything that needs a human decision. The web UI does the same from a form. With the API running (`make run`): +Post a Docker Compose file to the API and you get back Kubernetes Deployments and Services. The response also lists notes on anything you need to decide yourself. The web UI does the same through a form. Start the API with `make run`, then run: ```bash curl -s localhost:8000/convert/compose-to-k8s/yaml \ @@ -83,7 +85,7 @@ kind: Service protocol: TCP ``` -A CloudFormation template works the same way, with `/convert/cfn-to-terraform`: +To convert a CloudFormation template, post it to `/convert/cfn-to-terraform`: ```bash curl -s localhost:8000/convert/cfn-to-terraform \ @@ -107,11 +109,11 @@ resource "aws_s3_bucket_versioning" "logs_versioning" { | 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 | +| [API reference](docs/reference/api.md) | Endpoints, requests, responses, errors and 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 convert to Terraform | +| [Architecture](docs/architecture.md) | The project layout, the two services and how they run on Kubernetes | +| [CI/CD](docs/operations/ci-cd.md) | Workflows, image publishing and security scanning | +| [Deploying to your cluster](docs/operations/deploy.md) | How to run DevToolkit on your own Kubernetes cluster | | [Configuration](docs/configuration.md) | Environment variables | -| [Roadmap](docs/roadmap.md) | Planned features in priority order, timeline, out of scope | +| [Roadmap](docs/roadmap.md) | Planned features in priority order, the timeline and what is out of scope | diff --git a/SECURITY.md b/SECURITY.md index 3ac96cc..af47143 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,13 +2,13 @@ ## Supported versions -Only the latest code on `main` (and the image tagged `latest`) gets security fixes. +Security fixes go to the latest code on `main` and to the image tagged `latest`. ## Reporting a vulnerability **Please report security problems privately.** -Report through GitHub: go to the **Security** tab of this repository and click **Report a vulnerability**. Only the maintainers can see the report. +Go to the **Security** tab of this repository on GitHub and click **Report a vulnerability**. Only the maintainers can see the report. Please include: @@ -16,17 +16,17 @@ Please include: - steps or an input that reproduces it - what an attacker could do with it -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. +We acknowledge each report within 7 days. Once a fix is released, we credit you in the advisory. Tell us if you would rather stay anonymous. ## Scope In scope: -- the `converter-api` service, e.g. input that crashes it, hangs it or makes it use excessive memory -- the Dockerfile and Kubernetes manifests in `k8s/` +- the `converter-api` service, for example input that crashes it, hangs it or makes it use too much memory +- the Dockerfiles and the Kubernetes manifests in `k8s/` - the GitHub Actions workflows in `.github/workflows/` Out of scope: -- deployments run by other people with their own configuration -- denial of service by sending a very large number of requests: this project leaves rate limiting to the platform it runs on +- deployments that other people run with their own configuration +- denial of service through a very large number of requests: rate limiting is the job of the platform that runs the service diff --git a/docs/README.md b/docs/README.md index 29158cd..6a0f7d2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,28 +1,28 @@ # DevToolkit documentation -Start with the [main README](../README.md) for the quick start. Everything else is here. +The [main README](../README.md) has the quick start. The pages below cover the rest. ## Using it -- [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 +- [API reference](reference/api.md): endpoints, request and response formats, errors and 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 convert to Terraform ## How it is built -- [Architecture](architecture.md): the two services, project layout and how they run on Kubernetes +- [Architecture](architecture.md): the two services, the project layout and how they run on Kubernetes ## Running it -- [CI/CD](operations/ci-cd.md): what runs on each PR and merge, image publishing, dependency and security scanning -- [Deploying to your cluster](operations/deploy.md): run it on any Kubernetes cluster +- [CI/CD](operations/ci-cd.md): what runs on each PR and merge, image publishing and dependency and security scanning +- [Deploying to your cluster](operations/deploy.md): how to run DevToolkit on your own Kubernetes cluster - [Configuration](configuration.md): environment variables ## Where it is going -- [Roadmap](roadmap.md): planned features in priority order, timeline and what is out of scope +- [Roadmap](roadmap.md): planned features in priority order, the timeline and what is out of scope ## Contributing -- [CONTRIBUTING.md](../CONTRIBUTING.md): local setup, adding a converter or service, code style, PR process -- [SECURITY.md](../SECURITY.md): reporting a vulnerability +- [CONTRIBUTING.md](../CONTRIBUTING.md): local setup, how to add a converter or a service, code style and the PR process +- [SECURITY.md](../SECURITY.md): how to report a vulnerability diff --git a/docs/architecture.md b/docs/architecture.md index 887a789..1716ec9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,9 +5,9 @@ | Service | What it does | Port | Reachable from | |---------|--------------|------|----------------| | `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 | +| `converter-api` | Runs the conversions behind a JSON API | 8000 | `web` only | -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. +Only `web` calls `converter-api`. In the cluster, a [NetworkPolicy](../k8s/converter-api/networkpolicy.yaml) lets only `web` pods reach it. This way `web` is the one place that reads user input and renders pages. The API can change freely behind it. ## Project layout @@ -67,7 +67,7 @@ services/ 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 + tests/ pytest tests, run against a fake converter-api Dockerfile Multi-stage build: Python deps, Tailwind CLI, Node (editor), runtime k8s/ namespace.yaml devtoolkit namespace @@ -83,7 +83,7 @@ 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 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. +Conversion logic lives in `converter-api/converters/`, as classes and 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. ## How it runs on Kubernetes @@ -102,17 +102,26 @@ The manifests in `k8s/` are plain YAML. Both services follow the same pattern: 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. -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. +The readiness probe of `web` checks only `web`. When the API is down, the pages stay up and show an error. Each service stays in rotation based 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. +Both Dockerfiles use the official slim Python image and run as UID 10001. Each Dockerfile sets the exact Python version. Dependabot keeps it current. Each image has a Docker `HEALTHCHECK` for plain `docker run`. Kubernetes uses its own probes. - `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 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. +- `services/web/Dockerfile`: the same two stages plus two more. The **css** stage downloads the standalone Tailwind CLI (version and SHA-256 pinned in the Dockerfile) and compiles `styles/input.css` into one small stylesheet. The **editor** stage bundles the CodeMirror editor from `editor/` with esbuild, after `npm ci` against the committed lockfile. The runtime image gets only their output. + +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). ## How a page works -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`. +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 only the result fragment (`_result.html`, `_terraform_result.html` or `_validation.html`). The script then: + +- swaps the fragment into the page +- turns the file list into tabs +- mounts a read-only editor for each file +- marks the error line in the input editor, from the `data-error-line` attribute of the fragment -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). +The zip downloads are plain form posts to `/compose-to-k8s/zip` and `/cfn-to-terraform/zip`. diff --git a/docs/configuration.md b/docs/configuration.md index 820f63c..3b3d9e8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,12 +1,12 @@ # Configuration -Both services are configured with environment variables. +You configure both services with environment variables. ## converter-api | 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 makes the service log a warning and use `info`. | +| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, `error`, `critical` (any case) | How much the service logs. `info` logs rejected conversions and `debug` adds more detail. With an unknown value, the service logs a warning and uses `info`. | The service always listens on port **8000**. @@ -14,9 +14,9 @@ The service always listens on port **8000**. | Variable | Default | Allowed values | What it does | |----------|---------|----------------|--------------| -| `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, which exists on Google Cloud. | +| `LOG_LEVEL` | `info` | As for `converter-api` | As for `converter-api`. Even at `error`, the service logs each time it cannot reach `converter-api`. | +| `CONVERTER_API_URL` | `http://localhost:8000` | A URL | The address of `converter-api`. In the cluster this is `http://converter-api:8000`, after the Service name. | +| `CONVERTER_API_AUTH` | `none` | `none`, `google` | `google` sends a Google identity token with each API call. Use it when `converter-api` requires authentication, as on Google Cloud Run. The token comes from the Google metadata server, so this works on Google Cloud only. | The service always listens on port **8080**. @@ -24,10 +24,10 @@ The service always listens on port **8080**. | How you run it | Where | |----------------|-------| -| Kubernetes | `k8s/converter-api/configmap.yaml` and `k8s/web/configmap.yaml`. After changing one, run `kubectl -n devtoolkit rollout restart deployment/` so the pods pick it up. | +| Kubernetes | `k8s/converter-api/configmap.yaml` and `k8s/web/configmap.yaml`. After you change one, run `kubectl -n devtoolkit rollout restart deployment/` so the pods pick up the change. | | Locally with Python | `LOG_LEVEL=debug make run`, `CONVERTER_API_URL=http://localhost:8000 make run-web` | | Plain Docker | `docker run -e LOG_LEVEL=debug ...` | ## Fixed limits -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. +The input limits (characters, nesting depth and value count) are set in code. See [API reference: input limits](reference/api.md#input-limits). `web` checks the input length before it calls the API and shows a clear 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 5038876..e6246d3 100644 --- a/docs/operations/ci-cd.md +++ b/docs/operations/ci-cd.md @@ -1,46 +1,46 @@ # CI/CD -All automation runs in GitHub Actions, from `.github/workflows/`. +All automation runs in GitHub Actions. The workflows are in `.github/workflows/`. ## 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) | +| `ci.yaml` | PR to `main`, push to `main` | Lint, tests, Docker builds, manifest validation and a deploy to a real cluster (see the jobs below) | | `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 -Every job covers both services. The list of services is one line at the top of `ci.yaml`. +Every job covers both services. The list of services is a single line at the top of `ci.yaml`. | Job | Checks | |-----|--------| -| `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 | +| `lint` | `ruff check` and `ruff format --check` on each service, then `scripts/check_code_rules.py` on the whole repo, which checks the code rules and writing rules in [CONTRIBUTING](../../CONTRIBUTING.md) | +| `test` | pytest on each service. The job fails when either service is below **95%** coverage | +| `build` | Builds both Docker images, starts them on one Docker network and runs a conversion through the web UI. This proves that `web` can call `converter-api` | | `validate-k8s` | [kubeconform](https://github.com/yannh/kubeconform) `-strict` on `k8s/` (the maintained successor to kubeval) | -| `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 | +| `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 the job 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/` and waits for both rollouts. It then uses the UI through the `web` Service, including a conversion. Last, it checks the NetworkPolicy: a `web` pod can reach `converter-api` and a pod without the `web` label is blocked | -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. +A new push to a PR cancels the runs for the previous push. 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` 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. +- **Passing commits only:** images are built only for commits that pass every CI job. +- **Changed services only:** a service image is built only when `services//` changed in that push. A commit that touches only docs or `k8s/` builds no images. ## 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 has no effect on what runs | +| Pinned actions | Every third-party action is pinned to a full commit SHA, with the version in a comment. A moved or hijacked tag cannot change what runs | | Pinned Tailwind CLI | The `web` Dockerfile downloads a fixed version and checks its SHA-256 before using it | | 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 | +| Locked editor bundle | `services/web/editor/package-lock.json` pins the exact npm dependencies of the code editor. The image build installs them with `npm ci` and 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 and each major bump gets its own PR. | +| CodeQL | Runs the `security-extended` queries on the Python code and 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 d46bfb9..730a43e 100644 --- a/docs/operations/deploy.md +++ b/docs/operations/deploy.md @@ -1,13 +1,13 @@ # 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 pulling needs no registry credentials. +The manifests in `k8s/` work on any conformant Kubernetes cluster: a local one, GKE, EKS, AKS or self-hosted. The published images are public, so your nodes can pull them without 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, 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`. +- A CNI that enforces NetworkPolicy, so that only `web` can reach `converter-api`. kindnet (the kind default), Calico, Cilium and GKE Dataplane V2 enforce it. Other CNIs accept the policy but ignore it. +- `kubectl` pointed at your cluster, with permission to create a namespace. +- Nodes that can pull from `ghcr.io`. ## Deploy @@ -29,9 +29,9 @@ This creates: ## Pin a version -The manifests use the `:latest` images. For anything you care about, pin exact builds: every commit on `main` that changed a service has an image tagged with its full commit SHA. +The manifests use the `:latest` images. For a deployment you rely on, pin exact builds. Every commit on `main` that changed a service has an image tagged with its full commit SHA. -Pin it in the manifest itself, before applying, so a later `kubectl apply` keeps the version: +Set the tag in the manifest before you apply it, so a later `kubectl apply` keeps the version: ```bash sed -i 's#/converter-api:latest#/converter-api:#' k8s/converter-api/deployment.yaml @@ -39,17 +39,17 @@ sed -i 's#/web:latest#/web:#' k8s/web/deployment.yaml kubectl apply -f k8s/converter-api/ -f k8s/web/ ``` -(`kubectl set image` also works, but the next `kubectl apply` of the unedited manifest silently switches back to `:latest`.) +`kubectl set image` also works, but the next `kubectl apply` of the unedited manifest switches back to `:latest` without warning. ## Try it -The Services are internal to the cluster (ClusterIP). To use the web UI from your machine: +The Services are ClusterIP, so they are reachable only inside the cluster. To use the web UI from your machine, run: ```bash kubectl -n devtoolkit port-forward svc/web 8080:8080 ``` -Then open http://localhost:8080. Public access through Ingress/Gateway with TLS is up to your cluster; point it at the `web` Service only. +Then open http://localhost:8080. For public access, set up an Ingress or Gateway with TLS in your cluster and point it at the `web` Service only. ## Configure diff --git a/docs/reference/api.md b/docs/reference/api.md index e2679f9..fb166e0 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -1,8 +1,8 @@ # API reference -While the service is running, interactive docs (Swagger UI) are served at `/docs`, e.g. http://localhost:8000/docs. +While the service runs, it serves interactive docs (Swagger UI) at `/docs`, for example http://localhost:8000/docs. -The `web` service calls these endpoints from the server side. In the cluster, a NetworkPolicy allows only `web` pods to reach the API; in the hosted version, the API requires authentication and only `web` is allowed to call it. To use the API directly, run it yourself (`make run`). +The `web` service calls these endpoints from its server. In the cluster, a NetworkPolicy lets only `web` pods reach the API. In the hosted version, the API requires authentication and only `web` may call it. To call the API yourself, run it locally with `make run`. ## Endpoints @@ -10,15 +10,15 @@ The `web` service calls these endpoints from the server side. In the cluster, a |--------|------|--------------| | GET | `/health` | Liveness probe: `{"status": "healthy"}` | | 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/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 | +| POST | `/convert/compose-to-k8s` | Converts Compose YAML and returns the manifests as JSON | +| POST | `/convert/compose-to-k8s/yaml` | The same conversion, returned as one multi-document YAML string | +| POST | `/convert/compose-to-k8s/files` | The same conversion, returned as files: one per resource or a Helm chart | +| POST | `/convert/cfn-to-terraform` | Converts a CloudFormation, AWS SAM or AWS CDK template to Terraform files | +| POST | `/validate/yaml` | Checks YAML syntax and reports the line and column of an error | ## Convert -Both convert endpoints take the same request: +The three `compose-to-k8s` endpoints take the same request: ```json { @@ -30,9 +30,9 @@ Both convert endpoints take the same request: | Field | Required | Default | Notes | |-------|----------|---------|-------| -| `compose_yaml` | yes | | The docker-compose file as a string | +| `compose_yaml` | yes | | The Docker Compose file as a string | | `namespace` | no | `default` | Must be a valid Kubernetes namespace name | -| `include_service` | no | `true` | `false` skips generating Services | +| `include_service` | no | `true` | `false` leaves out the Services | **Success** (HTTP 200), from `/convert/compose-to-k8s`: @@ -44,11 +44,11 @@ Both convert endpoints take the same request: } ``` -`manifests` has four lists, each possibly empty: `namespaces`, `persistent_volume_claims`, `deployments`, `services`. +`manifests` has four lists, any of which can be empty: `namespaces`, `persistent_volume_claims`, `deployments` and `services`. -`/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/yaml` returns `"yaml": "apiVersion: v1\n..."` instead of `manifests`. The string holds every resource in apply order (Namespace, PersistentVolumeClaims, Deployments, Services), separated by `---`. -`/convert/compose-to-k8s/files` takes one more field, `output`: `manifests` (the default) or `helm`. It returns the result as files: +`/convert/compose-to-k8s/files` takes one more field, `output`, set to `manifests` (the default) or `helm`. It returns the result as files: ```json { @@ -62,13 +62,13 @@ Both convert endpoints take the same request: } ``` -With `output: helm` the files are `Chart.yaml`, `values.yaml` and `templates/*.yaml`. An unknown `output` is a 422. +With `output: helm`, the files are `Chart.yaml`, `values.yaml` and `templates/*.yaml`. An unknown `output` value returns a 422. -`notes` lists anything that needs a human decision. See [conversion rules](conversion-rules.md). +`notes` lists anything you need to decide or fix yourself. 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. +`POST /convert/cfn-to-terraform` converts a CloudFormation template (JSON or YAML), an AWS SAM template or the template that `cdk synth` writes. [CloudFormation to Terraform](cloudformation-to-terraform.md) explains how each part converts. ```json { @@ -83,10 +83,10 @@ With `output: helm` the files are `Chart.yaml`, `values.yaml` and `templates/*.y | 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` | +| `provider` | no | `aws` | `aws`: hand-written `aws` provider mappings, with `awscc` for the other types. `awscc`: `awscc` for every resource | | `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 | +| `stack_name` | no | | `AWS::StackName` converts to `var.stack_name` and this field sets its default. It starts with a letter, followed by letters, digits and `-`, up to 128 characters | +| `include_imports` | no | `false` | Also writes `imports.tf`, so Terraform can adopt the resources that an existing stack created | **Success** (HTTP 200): @@ -106,11 +106,13 @@ With `output: helm` the files are `Chart.yaml`, `values.yaml` and `templates/*.y } ``` -`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. +`source` is `cloudformation`, `sam` or `cdk`. `resources` lists each resource of the template after SAM expansion, with its Terraform address. A resource kept as a comment has the address `null` and the status `unsupported`. + +Errors have the same shape as for the other endpoints, with `line` and `column` for syntax errors. If the converter cannot handle the structure of a template, it returns a 400 that asks you to open an issue. ## Validate -`POST /validate/yaml` takes `{"yaml": "..."}`. Multi-document input (separated by `---`) is supported. +`POST /validate/yaml` takes `{"yaml": "..."}`. It accepts several documents separated by `---`. ```json {"valid": true, "documents": 2} @@ -124,12 +126,12 @@ With `output: helm` the files are `Chart.yaml`, `values.yaml` and `templates/*.y | Status | When | Body | |--------|------|------| -| 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 | +| 400 | The input cannot be converted: invalid YAML or JSON, a file without services or resources, a wrong field type or a bad value | `{"success": false, "error": "..."}` | +| 422 | The request itself is malformed: a missing field, a bad namespace or stack name, an unknown option or input that is too long | The standard FastAPI validation error | ## Input limits -Real files are far below these limits. They cap the CPU time and memory a single request can use. +These limits cap the CPU time and memory that one request can use. Real files stay far below them. | Limit | Compose and YAML check | CloudFormation | Response | |-------|------------------------|----------------|----------| diff --git a/docs/reference/cloudformation-to-terraform.md b/docs/reference/cloudformation-to-terraform.md index 7fb3bfe..436e702 100644 --- a/docs/reference/cloudformation-to-terraform.md +++ b/docs/reference/cloudformation-to-terraform.md @@ -1,22 +1,22 @@ # 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. +This page shows how a CloudFormation, AWS SAM or AWS CDK template converts to 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`. +As with the other converters, anything that converts only in part stays in the output as a comment and is listed in `notes`. ## Inputs | Input | How it is detected | What happens first | |-------|--------------------|--------------------| -| CloudFormation, JSON or YAML | The default | Nothing | +| CloudFormation, JSON or YAML | The default | The template converts as it is | | 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)) | +| AWS CDK | An `AWS::CDK::Metadata` resource or `aws:cdk:path` metadata | The converter removes CDK bookkeeping and takes names 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. +Logical IDs and the names of parameters, conditions, mappings and outputs must be letters and digits, as CloudFormation requires. That rule also makes 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"`. +The converter reads YAML short forms (`!Ref`, `!GetAtt A.B`, `!Sub`, `!If`...) as their long forms. It reads scalars the way CloudFormation does: `2010-09-09` stays a string and `0755` stays `"0755"`. ## Output files @@ -29,19 +29,21 @@ YAML short forms (`!Ref`, `!GetAtt A.B`, `!Sub`, `!If`...) are read as their lon | `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. +`layout: single` puts everything in `main.tf`. The output matches the formatting of `terraform fmt`. -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. +The providers read their region and credentials from the environment (`AWS_REGION`, `AWS_PROFILE`), as the AWS CLI does. This matches CloudFormation, where a stack gets its region when you deploy it. ## 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. +With `provider: aws` (the default), the [85 types below](#hand-written-mappings) use hand-written mappings to the `aws` provider. They produce the Terraform an experienced user would write. For example, the versioning of an S3 bucket converts to `aws_s3_bucket_versioning` and IAM inline policies convert to `aws_iam_role_policy`. -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. +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. For example, `AWS::Batch::JobQueue` maps to `awscc_batch_job_queue` and its property `ComputeEnvironmentOrder` maps to `compute_environment_order`. + +DevToolkit includes an index of the 1,713 types that awscc supports, built from the provider schema. The index has the exact resource and attribute names. It also marks the properties that are maps (their keys stay as written) and the properties that are JSON documents (written with `jsonencode`). The notes list any property that the installed awscc version lacks. Each awscc type in use also 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. +A type that neither provider covers is written as a comment with its properties and listed in the notes. This applies to custom resources, `AWS::CloudFormation::*` and the few types that awscc lacks. ## Parameters @@ -51,7 +53,7 @@ A type outside both (custom resources, `AWS::CloudFormation::*`, the few types a | `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 | +| `AWS::SSM::Parameter::Value<...>` | A variable with 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) }` | @@ -72,20 +74,20 @@ A parameter with a name Terraform reserves (`count`, `version`, `source`...) get | `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 | +| `!Join`, `!Select`, `!Split` | A template string where that reads better, else `join()`, `element()`, `split()`. Literal values are computed during the conversion | | `!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 | +| `!ImportValue name` | A variable `import_`, with a note, because stack exports exist only in CloudFormation | | `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. +A reference to a resource that was kept as a comment turns into a placeholder variable. The description of the variable names the resource and attribute it replaces, 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. +The converter removes `AWS::NoValue` the way CloudFormation does: from a list (`[for item in [...] : item if item != null]`), from a mapping (`merge({...}, cond ? {key = value} : {})`) and from a `!Join`. Some list items convert to their own resource, such as a policy ARN, a queue or a security group rule. When such an item is written as `!If [Cond, x, !Ref AWS::NoValue]`, its resource gets `count = local.cond ? 1 : 0`. Inside JSON documents, an `!If` whose branches have different shapes (a string or a list) is encoded per branch. ### Known limitations @@ -98,11 +100,11 @@ A reference to a resource that was left as a comment becomes a placeholder varia |----------------|-----------| | `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: Retain` | `lifecycle { prevent_destroy = true }`, with a note. Terraform then refuses to destroy the resource, while CloudFormation would delete the stack and keep the resource | | `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. +Some resources need a name in Terraform that CloudFormation would generate, such as a DynamoDB table, a Lambda function or an ECR repository. The converter names them `${var.stack_name}-` and adds a note. To adopt an existing resource, change the name to its current name. ## Hand-written mappings @@ -120,14 +122,14 @@ Where CloudFormation generates a name Terraform requires (a DynamoDB table, a La | 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: +The converter also handles these differences between CloudFormation and Terraform: -- A security group without egress rules gets the implicit allow-all egress rule of CloudFormation written out, because `aws_security_group` removes it. +- CloudFormation gives a security group without egress rules an implicit allow-all egress rule. `aws_security_group` removes that rule, so the converter writes it out. - 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. +- `AWS::Lambda::Version` converts to `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. +When a mapping leaves out a property, the property is written as a comment in the resource and listed in the notes. ## AWS SAM @@ -149,25 +151,25 @@ SAM resources expand with the logical IDs SAM uses, so references in the templat | `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. +The notes list `DeploymentPreference`, `Auth`, `Cors` (on REST APIs), `Domain`, `AWS::Serverless::Application` and any other setting that has no Terraform equivalent. ## 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. +- `autoDeleteObjects` converts to `force_destroy = true` on the bucket. The CDK helper function, 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`. +- For `restrictDefaultSecurityGroup`, a note tells you 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: +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. When the template gives the name of a resource as a literal, the import ID is that name. Otherwise it is `TODO`: replace it 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. +3. Delete the stack. The resources stay in place and Terraform now manages them. ## 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. +`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 any error or warning. CI runs it on every pull request. diff --git a/docs/reference/conversion-rules.md b/docs/reference/conversion-rules.md index 212b911..e68fa55 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: exactly the resources the compose file needs. +This page shows how each Docker Compose (v3) field converts to Kubernetes. The converter writes only the resources that the compose file needs. ## What is generated @@ -9,13 +9,13 @@ 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 internal (`external` unset) | -| `namespace` other than `default` | Namespace | The requested namespace is another one | +| `namespace` other than `default` | Namespace | You set `namespace` to another name | Files are written in apply order: Namespace, PersistentVolumeClaims, Deployments, Services. ## Field mapping -| docker-compose | Kubernetes | +| Docker Compose | Kubernetes | |----------------|------------| | `image` | `containers[].image` | | `build` (no `image`) | Image `:latest`, with a note to push it to a registry | @@ -51,9 +51,9 @@ Port ranges (`"3000-3005"`) return an error. | `memory: 1g` | `1Gi` | | `memory: 268435456` (bytes) | `256Mi` | -`cpus` must be at least `0.001`, because anything smaller would round to zero CPU. +`cpus` must be at least `0.001`, because a smaller value would round to zero CPU. -Every container gets requests and limits, because an unbounded pod is the one thing Kubernetes will happily schedule and then evict: +Every container gets requests and limits. Without them, Kubernetes still schedules the pod but may evict it when the node runs low on resources. The converter sets them like this: | Compose declares | Output | Note | |------------------|--------|------| @@ -72,7 +72,7 @@ Every container gets requests and limits, because an unbounded pod is the one th | `retries` | `failureThreshold` | | `start_period` | `initialDelaySeconds` | -The same probe is used for liveness and readiness. `test: ["NONE"]`, `disable: true` or a missing `test` produce no probes. Durations accept compose syntax (`1m30s`, `500ms`) and are rounded up to whole seconds. +The same probe serves for liveness and readiness. With `test: ["NONE"]`, `disable: true` or no `test`, the container gets no probes. Durations use compose syntax (`1m30s`, `500ms`) and are rounded up to whole seconds. ### Startup order @@ -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) has nothing to wait on, so it becomes a note. A dependency missing from the services of the file is an error. +When a dependency has no ports or Services are turned off, there is no port to wait on. The converter then adds a note in place of the init container. A `depends_on` entry that names a service missing from the file is an error. ### Volumes @@ -95,43 +95,43 @@ A dependency without ports (or with Services disabled) has nothing to wait on, s | `data:/x:ro` | Same, mounted `readOnly` | | `/tmp` (anonymous) | `emptyDir` + mount | | `{type: tmpfs, target: /run}` | `emptyDir` with `medium: Memory` | -| `./src:/app` or `/host/path:/x` (bind mount) | Not converted; reported as a note | -| Named volume declared `external: true` | Mounted as a claim that must already exist; no PVC generated | +| `./src:/app` or `/host/path:/x` (bind mount) | Left out and reported in the notes | +| Named volume declared `external: true` | Mounted from a claim with that name, which must already exist | -The PVC size is a placeholder and is reported as a note. A named volume mounted by more than one service becomes one PVC, with a note that ReadWriteOnce keeps those pods on the same node. +The PVC size is a placeholder that a note asks you to adjust. A named volume that several services mount becomes one PVC. A note then warns that with ReadWriteOnce, those pods must run on the same node. ## Notes for manual attention -`notes` lists what needs you: +`notes` lists what you need to check or change: | Compose | Note | |---------|------| -| 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 | +| Bind mount | The mount is left out. Use a ConfigMap, bake the files into the image or use a PVC | +| `depends_on` a service without ports | The converter adds no init container. Make the dependent service retry its connection | +| `networks` | Left out, because services reach each other by name (for example `http://db:5432`) | | `env_file` | Move the values into a ConfigMap or Secret | -| Env var with no value (`- API_KEY`) | Compose reads it from the host; set it or use a Secret | +| Env var with no value (`- API_KEY`) | Compose reads the value from the host. Set a value or use a Secret | | `build` without `image` | Push the image to a registry your cluster can pull from | -| No limits / only reservations | Placeholder or copied values were added; adjust them | -| Named volume | PVC size is a placeholder; shared volumes are ReadWriteOnce | +| No limits / only reservations | The converter adds placeholder values or copies the reservations. Adjust them | +| Named volume | The PVC size is a placeholder. A shared volume is ReadWriteOnce, so its pods must run on the same node | | External volume | A PVC with that name must already exist | ## 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 top-level `name` of the compose file, with `app` as the fallback. +With `output: helm`, the converter writes the same resources as a chart. The chart has a `Chart.yaml`, one template per resource and a `values.yaml` with what changes between environments: the image, replicas and resources of each service plus the size of each volume. The templates leave out the namespace, so Helm uses the release namespace. The chart takes its name from the top-level `name` of the compose file. Without a `name`, the chart is called `app`. ## 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. The converter fixes invalid names and adds a note: - `my_app` becomes `my-app` - `1api` becomes `svc-1api` -If two services end up with the same name, conversion fails with an error. +If two services end up with the same name, the conversion fails with an error. ## YAML parsing -Values are read the way Docker Compose reads them, with YAML 1.2 rules: +The converter reads values the way Docker Compose does, with YAML 1.2 rules: | Compose | YAML 1.1 would give | DevToolkit gives | |---------|---------------------|------------------| diff --git a/docs/roadmap.md b/docs/roadmap.md index 752fcd1..f904665 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,8 +1,8 @@ # Roadmap -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. +DevToolkit builds converters that **few other tools offer**. For common tasks such as Base64, JWT decoding or explaining cron expressions, use one of the many tools that already exist. -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. +The features below are in priority order. The [DevToolkit roadmap board](https://github.com/users/zainsohail88/projects/2/views/3) tracks them. The dates are targets. ## Timeline @@ -32,23 +32,23 @@ gantt | 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 | +| **Kubernetes → Docker Compose** | Deployments, Services, ConfigMaps → Compose services | Maintained tools convert only the other way, from Compose to Kubernetes | +| **Compose / Kubernetes ↔ AWS ECS** | Both directions between Compose, Kubernetes and ECS task definitions | Existing tools are out of date or cover only part of Compose | | **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 | +| **Firewall rules translator** | Any direction between AWS Security Groups, GCP firewall rules, Azure NSGs and Kubernetes NetworkPolicy | Existing tools leave out GCP and NetworkPolicy | +| **Prometheus alerts → Datadog / CloudWatch** | Prometheus alerting rules → Datadog monitors and CloudWatch alarms | Existing converters leave out Datadog and CloudWatch | -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. +Each new converter works like the existing ones. It reports anything it converts only in part in `notes`. It also gets a web page and an API endpoint. ## Later -- Ad-supported public hosting, from the original project vision. Revisit once the web UI has been live for a while. +- Ad-supported public hosting, an idea from the original project plan. We will look at it again 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 +- `web` (FastAPI + Jinja2 + Tailwind): a page per tool that calls the API from the server. Only `web` can reach the API - 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 @@ -56,7 +56,7 @@ Every converter follows the same rule as the existing ones: whatever it converts ## Dropped -- **`utility-api`** (Base64, JWT decode, cron explain, hashing). These tools are widely available already, so building them would add clutter. +- **`utility-api`** (Base64, JWT decode, cron explain, hashing). Many tools already do these jobs well, so building them here would only add clutter. ## Out of scope From 186e85a4c01389dc2fcbda6b485d6b1c41d22e34 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:30:12 +0000 Subject: [PATCH 4/5] Rewrite the CloudFormation converter messages for human readers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F --- .../converter-api/converters/cfn/awscc.py | 11 +- .../converter-api/converters/cfn/builder.py | 27 ++-- services/converter-api/converters/cfn/cdk.py | 20 +-- .../converter-api/converters/cfn/context.py | 56 +++++--- .../converter-api/converters/cfn/convert.py | 102 +++++++++----- .../converters/cfn/expressions.py | 49 +++++-- .../converter-api/converters/cfn/parse.py | 70 ++++++--- .../converter-api/converters/cfn/pipeline.py | 21 ++- .../converters/cfn/resources/apigateway.py | 15 +- .../converters/cfn/resources/compute.py | 29 ++-- .../converters/cfn/resources/data.py | 26 ++-- .../converters/cfn/resources/iam.py | 20 +-- .../converters/cfn/resources/messaging.py | 27 ++-- .../converters/cfn/resources/network.py | 69 +++++---- .../converters/cfn/resources/storage.py | 4 +- services/converter-api/converters/cfn/sam.py | 86 ++++++----- .../tests/test_cfn_apigateway.py | 32 ++--- services/converter-api/tests/test_cfn_cdk.py | 2 +- .../converter-api/tests/test_cfn_compute.py | 28 ++-- services/converter-api/tests/test_cfn_core.py | 133 ++++++++++-------- services/converter-api/tests/test_cfn_data.py | 12 +- services/converter-api/tests/test_cfn_iam.py | 26 ++-- .../converter-api/tests/test_cfn_messaging.py | 30 ++-- .../converter-api/tests/test_cfn_network.py | 51 ++++--- .../tests/test_cfn_observability.py | 12 +- .../tests/test_cfn_review_fixes.py | 8 +- services/converter-api/tests/test_cfn_sam.py | 56 ++++---- .../converter-api/tests/test_cfn_storage.py | 48 ++++--- services/web/tests/test_examples.py | 2 +- 29 files changed, 629 insertions(+), 443 deletions(-) diff --git a/services/converter-api/converters/cfn/awscc.py b/services/converter-api/converters/cfn/awscc.py index 0170b1a..d4300fb 100644 --- a/services/converter-api/converters/cfn/awscc.py +++ b/services/converter-api/converters/cfn/awscc.py @@ -99,8 +99,8 @@ def local_code(self, prop: str) -> None: ) 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" + f"{b.logical_id}: the awscc provider reads Lambda code only from S3. Zip {path}, " + f"upload it and set {bucket} and {key}. The aws provider zips the code for you." ) def value(self, value: Any, path: str) -> Any: @@ -151,9 +151,10 @@ def structure(self, value: dict[str, Any], path: str) -> dict[str, Any]: 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" + f"{self.b.logical_id} ({self.b.info.cfn_type}): {self.b.info.tf_type} in this " + f"awscc provider version has no argument for '{self.b.logical_id}.{child}', " + "so it was left out. Set it outside Terraform or try a newer provider " + "version." ) continue result[self.shapes.name(child, str(key))] = self.value(item, child) diff --git a/services/converter-api/converters/cfn/builder.py b/services/converter-api/converters/cfn/builder.py index d0fe4b8..2b38a08 100644 --- a/services/converter-api/converters/cfn/builder.py +++ b/services/converter-api/converters/cfn/builder.py @@ -89,10 +89,10 @@ def literal(self, name: str, kind: type, value: Any = MISSING) -> Any: 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" + f"{self.owner}: the value of '{self.where}.{name}' comes from a function, so the " + "converter left it out. Set it by hand." ) - self.comment(f"{name} was not converted: {snippet(value)}") + self.comment(f"{name} was left out. CloudFormation value: {snippet(value)}") return None def drop(self, name: str) -> None: @@ -197,10 +197,12 @@ def add_blocks( 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" + f"{self.owner}: '{where}' comes from a function, so the converter cannot turn it " + "into Terraform blocks. Set it by hand." + ) + self.comment( + f"{where.split('.', 1)[-1]} was left out. CloudFormation value: {snippet(value)}" ) - self.comment(f"{where.split('.', 1)[-1]} was not converted: {snippet(value)}") return inner = Props(self.ctx, value, where, self.owner) fill(inner) @@ -235,8 +237,11 @@ def finish(self) -> None: 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.ctx.note( + f"{self.owner}: the converter has no mapping for '{path}' yet, so it was left " + "out. Set it by hand if you need it." + ) + self.comment(f"{name} was left out. CloudFormation value: {snippet(value)}") self.values.clear() @@ -297,9 +302,9 @@ def name_attr(self, tf_name: str, cfn_name: str, lowercase: bool = False) -> Non 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)" + f"{self.logical_id}: the template leaves out {cfn_name}, so CloudFormation generated " + f"one. Terraform needs it, so the converter uses '-{suffix}'. To adopt " + "the existing resource, use its current name." ) def extra_name(self, suffix: str) -> str: diff --git a/services/converter-api/converters/cfn/cdk.py b/services/converter-api/converters/cfn/cdk.py index e09dad3..64b2b9d 100644 --- a/services/converter-api/converters/cfn/cdk.py +++ b/services/converter-api/converters/cfn/cdk.py @@ -200,8 +200,8 @@ def drop_bookkeeping(self) -> None: 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" + "This is a CDK template. The converter leaves out the CDK metadata and the bootstrap " + "version check. Resource names come from the construct paths." ) def replace_custom_resource(self, logical_id: str, resource: dict[str, Any]) -> None: @@ -223,7 +223,8 @@ def replace_custom_resource(self, logical_id: str, resource: dict[str, Any]) -> 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" + f"{logical_id} (CDK autoDeleteObjects) was replaced with force_destroy = true on " + "the bucket." ) elif kind == LOG_RETENTION: group = props.get("LogGroupName") @@ -235,13 +236,14 @@ def replace_custom_resource(self, logical_id: str, resource: dict[str, Any]) -> } 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" + f"{logical_id} (CDK logRetention) was replaced with a log group that has the same " + "retention. Import the existing log group first, because Terraform cannot create " + "one that already exists." ) 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" + f"{logical_id} (CDK restrictDefaultSecurityGroup) was left out. To get the same " + "effect, add an aws_default_security_group with no rules for the VPC." ) def remove_unused(self) -> None: @@ -282,8 +284,8 @@ def name_resources(self) -> None: (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" + "CDK assets: the converter reads Lambda code from cdk.out/asset.*. Run `cdk " + "synth` and keep cdk.out next to the Terraform files." ) diff --git a/services/converter-api/converters/cfn/context.py b/services/converter-api/converters/cfn/context.py index bbfb1ec..b79f524 100644 --- a/services/converter-api/converters/cfn/context.py +++ b/services/converter-api/converters/cfn/context.py @@ -84,19 +84,25 @@ def parameter_type(self, name: str) -> str: 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}'") + raise CfnError( + f"'Fn::FindInMap' points to the mapping '{name}', but the template has no mapping " + "with that 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}'") + raise CfnError( + f"The template uses the condition '{name}', but Conditions has no entry with that " + "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") + raise CfnError("'Ref' needs the name of a parameter or resource as a string.") if name == "AWS::NoValue": return None if name in PSEUDO_DATA: @@ -108,21 +114,28 @@ def ref(self, name: Any) -> Any: 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" + "AWS::StackId has no Terraform equivalent, so the converter uses the stack name " + "(var.stack_name) instead. Check that a name works where the template expects a " + "stack ID." ) return Raw("var.stack_name") if name == "AWS::NotificationARNs": - self.note("AWS::NotificationARNs has no Terraform equivalent and became []") + self.note( + "AWS::NotificationARNs has no Terraform equivalent, so the converter uses an " + "empty list. Add the SNS topic ARNs by hand if you need them." + ) 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(self.unresolved(info, "Ref", "The Ref value")) return Raw(info.expression(info.ref)) - raise CfnError(f"'Ref' refers to '{name}', which is no parameter or resource") + raise CfnError( + f"'Ref' points to '{name}', but the template has no parameter or resource with that " + "name." + ) def param_expression(self, name: str) -> str: """The expression for a parameter: its variable, or the SSM value it names.""" @@ -140,28 +153,38 @@ def get_att(self, args: Any) -> Any: resource, _, attribute = args.partition(".") args = [resource, attribute] if not isinstance(args, list) or len(args) != 2: - raise CfnError("'Fn::GetAtt' takes [resource, attribute]") + raise CfnError( + "'Fn::GetAtt' needs a resource and an attribute, written as [resource, " + "attribute] or '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}'") + raise CfnError( + f"'Fn::GetAtt' points to '{logical_id}', but the template has no resource with " + "that name." + ) 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" + f"Fn::GetAtt on '{logical_id}' builds its attribute name at deploy time, so the " + "value is null. Set it by hand." ) return None info = self.resources[logical_id] if info.kind == "unsupported": - return Raw(self.unresolved(info, attribute, f"the '{attribute}' attribute")) + 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") + raise CfnError( + f"'Fn::GetAtt' on '{logical_id}' asks for the attribute '{attribute}', but that " + "name is invalid. Use letters and digits, with dots between parts." + ) 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" + f"'{logical_id}.{attribute}' is converted to '{info.address}.{tf_attribute}'. " + "Check in the Terraform docs that this attribute exists." ) return Raw(info.expression(tf_attribute)) @@ -170,5 +193,6 @@ def unresolved(self, info: ResourceInfo, attribute: str, what: str) -> str: 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", + f"{what} of {info.logical_id} ({info.cfn_type}). The converter left that resource " + "out, so set this value by hand.", ) diff --git a/services/converter-api/converters/cfn/convert.py b/services/converter-api/converters/cfn/convert.py index 714c3e6..557d80b 100644 --- a/services/converter-api/converters/cfn/convert.py +++ b/services/converter-api/converters/cfn/convert.py @@ -82,7 +82,9 @@ def __init__( """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)}") + raise CfnError( + f"The provider '{provider}' is unknown. Use one of: {', '.join(PROVIDERS)}." + ) self.template = template self.ctx = Context(template, provider) self.stack_name = stack_name @@ -116,8 +118,8 @@ def parameters(self) -> None: 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)" + f"{description + ' ' if description else ''}(the name of the SSM parameter " + "that holds the value)" ).strip() if description: body.append(Attr("description", str(description))) @@ -166,7 +168,7 @@ def _validations(self, name: str, spec: dict[str, Any], tf_type: str) -> list[Bl rules.append( ( f"contains({hcl.inline(values)}, {ref})", - f"Must be one of: {', '.join(str(v) for v in values)}.", + f"The value must be one of: {', '.join(str(v) for v in values)}.", ) ) if tf_type == "string": @@ -175,7 +177,7 @@ def _validations(self, name: str, spec: dict[str, Any], tf_type: str) -> list[Bl rules.append( ( f"can(regex({hcl.quote('^(?:' + pattern + ')$')}, {ref}))", - f"Must match the pattern {pattern}.", + f"The value must match the pattern {pattern}.", ) ) for key, operator, words in ( @@ -187,7 +189,7 @@ def _validations(self, name: str, spec: dict[str, Any], tf_type: str) -> list[Bl rules.append( ( f"length({ref}) {operator} {limit}", - f"Must be {words} {limit} characters.", + f"The value must be {words} {limit} characters long.", ) ) if tf_type == "number": @@ -197,7 +199,9 @@ def _validations(self, name: str, spec: dict[str, Any], tf_type: str) -> list[Bl ): if spec.get(key) is not None: limit = parameter_default(spec[key], "number") - rules.append((f"{ref} {operator} {limit}", f"Must be {words} {limit}.")) + rules.append( + (f"{ref} {operator} {limit}", f"The value must be {words} {limit}.") + ) blocks = [] for condition, message in rules: text = sentence(str(constraint)) if constraint else message @@ -301,13 +305,14 @@ def convert_resources(self) -> None: self._import(info, resource) for cfn_type in sorted(awscc_types): reason = ( - "the awscc provider was requested" + "you chose the awscc provider" if self.ctx.provider == "awscc" - else "it has no hand-written aws mapping yet" + else "the converter has no aws provider mapping for it 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" + f"{cfn_type} is converted with the awscc provider because {reason}. The awscc " + f"arguments follow the CloudFormation schema, so check {awscc_type(cfn_type)} in " + "the awscc provider docs." ) def _resource_block(self, builder: Builder, resource: dict[str, Any]) -> Block: @@ -322,7 +327,10 @@ def _resource_block(self, builder: Builder, resource: dict[str, Any]) -> Block: 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}'") + raise CfnError( + f"'{info.logical_id}' has DependsOn '{target}', but the template has no " + "resource with that name." + ) if other.kind != "unsupported": addresses.append(Raw(other.address)) if addresses: @@ -332,17 +340,18 @@ def _resource_block(self, builder: Builder, resource: dict[str, Any]) -> Block: 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" + f"{info.logical_id} has DeletionPolicy {policy}, so the converter adds " + "prevent_destroy. `terraform destroy` then fails, while CloudFormation would " + "keep the resource. To let go of it, use a `removed` block with `destroy = " + "false`." ) 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" + f"{info.logical_id} has DeletionPolicy Snapshot, but Terraform takes no snapshot " + "on destroy. Take a snapshot by hand before you destroy it." ) # prevent_destroy also blocks replacement, so a Retain update policy is covered. if resource.get("UpdateReplacePolicy") == "Snapshot" or ( @@ -350,20 +359,21 @@ def _resource_block(self, builder: Builder, resource: dict[str, Any]) -> Block: and policy not in ("Retain", "RetainExceptOnCreate") ): self.ctx.note( - f"{info.logical_id} has UpdateReplacePolicy " - f"{resource['UpdateReplacePolicy']}: Terraform has no equivalent" + f"{info.logical_id}: UpdateReplacePolicy {resource['UpdateReplacePolicy']} has no " + "Terraform equivalent, so it was left out. Check `terraform plan` for " + "replacements before you apply." ) 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" + f"{info.logical_id}: {attribute} only works in CloudFormation, so it was left " + "out. Handle signals or rolling updates another way if you rely on it." ) 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" + f"{info.logical_id} uses AWS::CloudFormation::Init (cfn-init), which only runs in " + "CloudFormation. Move that setup into user_data (cloud-init) or an AMI." ) if lifecycle: meta.append(Block("lifecycle", [], lifecycle)) @@ -376,16 +386,27 @@ def _unsupported(self, info: ResourceInfo, resource: dict[str, Any]) -> None: 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" + why = ( + "Custom resources call a Lambda function or SNS topic during stack operations, " + "which only CloudFormation does. Rebuild that logic in Terraform or run it " + "another way." + ) elif info.cfn_type.startswith("AWS::CloudFormation::"): - why = "it exists inside CloudFormation only" + why = ( + "This type only exists inside CloudFormation. Replace it with a Terraform " + "feature, such as a module for a nested stack." + ) 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}") + why = ( + "Neither the aws mappings nor the awscc provider covers this type. Write the " + "Terraform resource by hand." + ) + self.ctx.note(f"{info.logical_id} ({info.cfn_type}) was left out. {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 {})}" + f"{info.logical_id} ({info.cfn_type}) was left out. See the notes for the " + "reason.\n" + f"CloudFormation properties: {snippet(resource.get('Properties') or {})}" ) ) @@ -400,7 +421,7 @@ def _import(self, info: ResourceInfo, resource: dict[str, Any]) -> None: 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}"), + Attr("id", identifier_value or f"TODO: the physical ID of {info.logical_id}"), ] self.imports.append(Block("import", [], body)) @@ -433,8 +454,8 @@ def convert_outputs(self) -> None: 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" + f"Output {name} is exported as '{shown}'. Terraform has no stack exports, so " + "other configurations read the output with terraform_remote_state." ) self.outputs.append(Block("output", [tf_name], body)) @@ -489,7 +510,9 @@ def _all_variables(self) -> list[Block]: if self.ctx.stack_name_used: name = "stack_name" body: list[Any] = [ - Attr("description", "Name of the stack (replaces AWS::StackName)"), + Attr( + "description", "The stack name, used wherever the template reads AWS::StackName" + ), Attr("type", Raw("string")), ] if self.stack_name: @@ -501,7 +524,7 @@ def _all_variables(self) -> list[Block]: 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)}") + raise CfnError(f"The layout '{layout}' is unknown. 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()) @@ -510,12 +533,13 @@ def files(self, layout: str) -> list[dict[str, str]]: if self.imports: import_blocks = [ Comment( - "Adopt the resources the stack created. Replace each TODO with the\n" - "physical ID of the resource:\n" + "These import blocks adopt the resources the stack already created.\n" + "Replace each TODO with the physical ID of the resource. To list them, run:\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." + "Most types import by that ID. The Import section in the Terraform docs of\n" + "each resource type says which ID it takes. Set DeletionPolicy: Retain on\n" + "every resource, then delete the stack once `terraform plan` shows no " + "changes." ) ] + self.imports if layout == "single": diff --git a/services/converter-api/converters/cfn/expressions.py b/services/converter-api/converters/cfn/expressions.py index 30eb8fc..0f7df6b 100644 --- a/services/converter-api/converters/cfn/expressions.py +++ b/services/converter-api/converters/cfn/expressions.py @@ -69,7 +69,7 @@ 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") + raise CfnError(f"'{function}' needs a list of {expected} values. Check its arguments.") return args @@ -110,7 +110,10 @@ def check_json_depth(value: Any) -> None: while stack: node, depth = stack.pop() if depth > MAX_JSON_DEPTH: - raise CfnError("A JSON document in the template is nested too deeply") + raise CfnError( + "A JSON document in the template nests too deeply. Reduce the nesting and try " + "again." + ) if isinstance(node, dict): stack.extend((item, depth + 1) for item in node.values()) elif isinstance(node, list): @@ -188,7 +191,9 @@ def parameter_type(self, name: str) -> str: 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") + raise CfnError( + "An expression in the template nests too deeply. Reduce the nesting and try again." + ) if isinstance(value, Expression): return Raw(value.text) if isinstance(value, dict): @@ -280,7 +285,10 @@ 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") + self.note( + f"The intrinsic function '{function}' has no Terraform conversion, so the value " + "is null. Set it by hand." + ) return None return handler(args, depth) @@ -303,10 +311,10 @@ def fn_sub(self, args: Any, depth: int) -> Any: 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}]") + raise CfnError("'Fn::Sub' needs a string or a [string, {variables}] pair.") args, variables = args if not isinstance(args, str): - raise CfnError("'Fn::Sub' needs a string") + raise CfnError("'Fn::Sub' needs a string as its template text.") pieces: list[Any] = [] position = 0 for match in SUB_VARIABLE.finditer(args): @@ -356,7 +364,10 @@ def fn_select(self, args: Any, depth: int) -> Any: 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") + raise CfnError( + f"'Fn::Select' asks for index {position}, which is past the end of the list. " + "Indexes start at 0." + ) return self.expr(items[position], depth) return Raw(f"element({self.text(items)}, {hcl.inline(self.expr(index, depth))})") @@ -370,7 +381,10 @@ def fn_split(self, args: Any, depth: int) -> Any: 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") + self.note( + "Fn::GetAZs asks for another region. Terraform reads the zones of the current " + "region instead. Set the zones by hand if you need that region." + ) address = self.data("aws_availability_zones", "available", [Attr("state", "available")]) return Raw(f"{address}.names") @@ -387,7 +401,7 @@ def fn_cidr(self, args: Any, depth: int) -> Any: 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") + raise CfnError(f"'Fn::Cidr' can make at most {MAX_CIDR_COUNT} blocks. Lower the count.") 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)) @@ -408,7 +422,10 @@ def literal_cidr(self, block: str, count: int, bits: int) -> list[str]: break return subnets except ValueError as exc: - raise CfnError(f"'Fn::Cidr' is unable to split '{block}' that way") from exc + raise CfnError( + f"'Fn::Cidr' cannot split '{block}' that way. Check the CIDR block, the count and " + "the number of host bits." + ) from exc def fn_find_in_map(self, args: Any, depth: int) -> Any: """Fn::FindInMap, with lookup() when a DefaultValue is given.""" @@ -470,7 +487,7 @@ def fn_or(self, args: Any, depth: int) -> Any: 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") + raise CfnError(f"'{function}' needs 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)) @@ -488,11 +505,12 @@ def fn_import_value(self, args: Any, depth: int) -> Any: 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)", + f"The value of the CloudFormation export '{export}' (from 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" + f"Fn::ImportValue '{export}' reads a CloudFormation export. Terraform has no exports " + f"of its own, so the converter adds {variable} for it. Pass the value in or read it " + "with terraform_remote_state or a data source." ) return Raw(variable) @@ -510,6 +528,7 @@ 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" + f"Fn::Transform ({name or 'a macro'}) only runs inside CloudFormation, so the value " + "is null. Set it by hand." ) return None diff --git a/services/converter-api/converters/cfn/parse.py b/services/converter-api/converters/cfn/parse.py index 7815365..90fef12 100644 --- a/services/converter-api/converters/cfn/parse.py +++ b/services/converter-api/converters/cfn/parse.py @@ -107,7 +107,12 @@ def construct_tag(loader: yaml.SafeLoader, suffix: str, node: yaml.Node) -> dict 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) + raise CfnError( + f"The YAML tag '!{suffix}' is unknown. Use a CloudFormation tag such as !Ref, !Sub or " + "!GetAtt.", + 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(".") @@ -125,7 +130,7 @@ def syntax_error(exc: yaml.YAMLError) -> CfnError: 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) + return CfnError(f"The YAML has a syntax error: {problem}. Fix it and try again.", line, column) # CloudFormation's rule for logical IDs, and for parameter, condition, mapping and output @@ -142,11 +147,17 @@ def check_shape(data: Any) -> None: node, depth = stack.pop() count += 1 if count > MAX_NODES: - raise CfnError(f"Template too large: more than {MAX_NODES:,} values") + raise CfnError( + f"The template has more than {MAX_NODES:,} values. Split it into smaller templates." + ) if depth > MAX_DEPTH: - raise CfnError("Template nested too deeply") + raise CfnError( + "The template nests values too deeply. Reduce the nesting and try again." + ) if isinstance(node, float) and not math.isfinite(node): - raise CfnError(f"Invalid number in template: {node}") + raise CfnError( + f"The number {node} in the template is infinite or undefined. Use a finite number." + ) if isinstance(node, dict): stack.extend((k, depth + 1) for k in node) stack.extend((v, depth + 1) for v in node.values()) @@ -160,9 +171,12 @@ def load_template(text: str) -> dict[str, Any]: Raises CfnError with a message for the user. """ if not text or not text.strip(): - raise CfnError("Input is empty") + raise CfnError("The template is empty. Add a CloudFormation template in JSON or YAML.") if len(text) > MAX_TEMPLATE_CHARS: - raise CfnError(f"Template is longer than {MAX_TEMPLATE_CHARS:,} characters") + raise CfnError( + f"The template is longer than {MAX_TEMPLATE_CHARS:,} characters. Split it into " + "smaller templates." + ) stripped = text.lstrip(" \t\r\n") if stripped.startswith("{"): try: @@ -170,9 +184,13 @@ def load_template(text: str) -> dict[str, Any]: 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 + raise CfnError( + f"The JSON has a syntax error: {exc.msg}. Fix it and try again.", line, exc.colno + ) from exc except RecursionError as exc: - raise CfnError("Template nested too deeply") from exc + raise CfnError( + "The template nests values too deeply. Reduce the nesting and try again." + ) from exc else: try: check_yaml_limits(text, max_depth=MAX_DEPTH, max_nodes=MAX_NODES) @@ -187,7 +205,11 @@ def load_template(text: str) -> dict[str, Any]: # 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 + raise CfnError( + getattr( + exc, "message", "The template is too large. Split it into smaller templates." + ) + ) from exc check_shape(data) validate_template(data) return data @@ -197,37 +219,43 @@ 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") + raise CfnError( + "The top level of the template must be a mapping of sections, such as Resources and " + "Parameters." + ) resources = data.get("Resources") if not resources: - raise CfnError("Invalid template: no 'Resources' defined") + raise CfnError("The template needs a 'Resources' section with at least one resource.") if not isinstance(resources, dict): - raise CfnError("Invalid template: 'Resources' must be a mapping") + raise CfnError("The 'Resources' section must be a mapping from logical IDs to resources.") for logical_id, resource in resources.items(): if not isinstance(resource, dict): - raise CfnError(f"Invalid template: resource '{logical_id}' must be a mapping") + raise CfnError(f"The resource '{logical_id}' must be a mapping with at least a 'Type'.") kind = resource.get("Type") if not isinstance(kind, str) or not kind: - raise CfnError(f"Invalid template: resource '{logical_id}' has no 'Type'") + raise CfnError(f"The resource '{logical_id}' needs a 'Type', such as AWS::S3::Bucket.") 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") + raise CfnError( + f"The 'Properties' of '{logical_id}' must be a mapping from property names to " + "values." + ) 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") + raise CfnError(f"The '{section}' section must be a mapping from names to entries.") 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'") + raise CfnError(f"The parameter '{name}' needs a 'Type', such as String or Number.") 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'") + raise CfnError(f"The 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)" + f"The name '{name}' in {section} can only use letters and digits (A-Z, a-z, " + "0-9). Remove other characters, such as dashes or underscores." ) diff --git a/services/converter-api/converters/cfn/pipeline.py b/services/converter-api/converters/cfn/pipeline.py index 2c15448..cf77943 100644 --- a/services/converter-api/converters/cfn/pipeline.py +++ b/services/converter-api/converters/cfn/pipeline.py @@ -33,9 +33,11 @@ def __init__( 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)}") + raise CfnError( + f"The provider '{provider}' is unknown. Use one of: {', '.join(PROVIDERS)}." + ) if layout not in LAYOUTS: - raise CfnError(f"Unknown layout '{layout}'. Use one of: {', '.join(LAYOUTS)}") + raise CfnError(f"The layout '{layout}' is unknown. Use one of: {', '.join(LAYOUTS)}.") self.provider = provider self.layout = layout self.stack_name = stack_name @@ -55,8 +57,8 @@ def convert(self, text: str) -> dict[str, Any]: 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" + "The Rules section of the template was left out. Add its checks as validation " + "blocks on the variables or as preconditions." ) converter = Converter( template, self.provider, self.stack_name, self.include_imports, names, hints @@ -73,14 +75,19 @@ def convert(self, text: str) -> dict[str, Any]: 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" + ( + f"The top-level section '{name}' is unknown to CloudFormation, so the converter " + "ignored it. Check the spelling if you meant a CloudFormation section." + ) 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" + f"The transform '{name}' runs inside CloudFormation, so the converter cannot " + "apply it. Convert the processed template instead. Get it with `aws " + "cloudformation get-template --stack-name --template-stage " + "Processed`." ) return notes diff --git a/services/converter-api/converters/cfn/resources/apigateway.py b/services/converter-api/converters/cfn/resources/apigateway.py index 4f3001a..7c04971 100644 --- a/services/converter-api/converters/cfn/resources/apigateway.py +++ b/services/converter-api/converters/cfn/resources/apigateway.py @@ -34,8 +34,9 @@ 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}/")' + f"{b.logical_id}: BodyS3Location was left out, because Terraform reads the body from " + "a local file. Download the OpenAPI file next to the Terraform files and set body = " + 'file("${path.module}/").' ) @@ -136,9 +137,9 @@ def convert(self, b: Builder) -> None: 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" + f"{b.logical_id}: Terraform only redeploys a deployment when its arguments " + "change. Add triggers, such as 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") @@ -224,8 +225,8 @@ def method_settings( 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" + f"{b.logical_id}: MethodSettings[{index - 1}] computes its path or method, so " + "method_path is '*/*'. Set the right path by hand." ) path = "*/*" inner.boolean("metrics_enabled", "MetricsEnabled") diff --git a/services/converter-api/converters/cfn/resources/compute.py b/services/converter-api/converters/cfn/resources/compute.py index fbd0a79..319e02e 100644 --- a/services/converter-api/converters/cfn/resources/compute.py +++ b/services/converter-api/converters/cfn/resources/compute.py @@ -141,9 +141,9 @@ def convert(self, p: Props, cfn_name: str) -> None: 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)" + f"{b.logical_id}: the inline code uses the cfn-response module, which only " + "CloudFormation adds to ZipFile code. 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)] @@ -503,14 +503,14 @@ def convert(self, b: Builder) -> None: } 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" + f"function itself. The converter sets publish = true on {info.address}. " + f"{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" + "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"))) @@ -627,8 +627,8 @@ def devices(self, b: Builder, p: Props) -> None: 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" + f"{b.logical_id}: the converter treats block device '{device}' as " + "root_block_device. Check that it is the root device of the AMI." ) else: kind = "ebs_block_device" @@ -657,11 +657,12 @@ def primary_interface(self, b: Builder, p: Props) -> None: 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" + f"{snippet(keep)}, but Terraform always deletes the interface it creates with the " + "instance. To keep the interface, create an aws_network_interface and attach it." + ) + inner.comment( + f"DeleteOnTermination was left out. CloudFormation value: {snippet(keep)}" ) - 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") @@ -840,8 +841,8 @@ def namespace(self, value: Any) -> Any: 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" + "which CloudFormation looks up or creates. Terraform needs the namespace ARN, " + "for example from an aws_service_discovery_http_namespace." ) return b.ctx.expr(value) diff --git a/services/converter-api/converters/cfn/resources/data.py b/services/converter-api/converters/cfn/resources/data.py index a87a0c8..39e8916 100644 --- a/services/converter-api/converters/cfn/resources/data.py +++ b/services/converter-api/converters/cfn/resources/data.py @@ -47,8 +47,8 @@ def _final_snapshot(b: Builder, identifier_prop: str) -> list[Attr]: 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'" + f"{b.logical_id}: CloudFormation snapshots this database on delete by default. " + f"Terraform does the same here and names the snapshot '{base}-final-snapshot'." ) return [ Attr("skip_final_snapshot", False), @@ -60,9 +60,9 @@ 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" + f"{b.logical_id}: the master password ends up in the Terraform state. Use " + "manage_master_user_password = true (a Secrets Manager secret) or the write-only " + f"{tf_name}_wo argument instead." ) @@ -259,9 +259,9 @@ def convert(self, b: Builder) -> None: 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)" + f"{b.logical_id}: the provider applies parameters immediately, which fails " + 'for a static parameter. Set apply_method = "pending-reboot" on those, so ' + "they take effect at the next reboot as in CloudFormation." ) p.tags() @@ -409,14 +409,14 @@ def convert(self, b: Builder) -> None: [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" + f"{b.logical_id}: the secret value ends up in the Terraform state. Consider the " + "write-only secret_string_wo argument instead." ) 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" + f"{b.logical_id}: GenerateSecretString has no aws provider equivalent. Generate " + "the value with an ephemeral random_password and secret_string_wo. You can also " + "convert this secret with the awscc provider." ) def fill_replica(self, r: Props) -> None: diff --git a/services/converter-api/converters/cfn/resources/iam.py b/services/converter-api/converters/cfn/resources/iam.py index bdf9d83..689d07e 100644 --- a/services/converter-api/converters/cfn/resources/iam.py +++ b/services/converter-api/converters/cfn/resources/iam.py @@ -65,10 +65,12 @@ def _inline_policies(b: Builder, kind: str) -> None: 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" + f"{b.logical_id}: inline policy {index} comes from a function, so the converter " + f"left it out. Add it as a {tf_type} by hand." + ) + b.props.comment( + f"Policies[{index - 1}] was left out. CloudFormation value: {snippet(item)}" ) - 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}" @@ -89,10 +91,10 @@ def _managed_policies(b: Builder, kind: str) -> None: _, 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" + f"{b.logical_id}: ManagedPolicyArns comes from a function, so the converter left it " + "out. Attach the policies by hand." ) - b.props.comment(f"ManagedPolicyArns was not converted: {snippet(arns)}") + b.props.comment(f"ManagedPolicyArns was left out. CloudFormation value: {snippet(arns)}") return suffixes = UniqueNames() for index, item in enumerate(arns, 1): @@ -186,11 +188,11 @@ def convert(self, b: Builder) -> None: 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", + f"The role to attach {b.logical_id} (AWS::IAM::Policy) to", ) b.ctx.note( - f"{b.logical_id} lists no role, user or group Terraform can read; it is " - f"attached to {variable} instead" + f"{b.logical_id} names no role, user or group that Terraform can read, so the " + f"converter attaches it to {variable}. Set that variable to the role name." ) principals = [("role", Raw(variable), None, None)] suffixes = UniqueNames() diff --git a/services/converter-api/converters/cfn/resources/messaging.py b/services/converter-api/converters/cfn/resources/messaging.py index c0ab3b4..c397309 100644 --- a/services/converter-api/converters/cfn/resources/messaging.py +++ b/services/converter-api/converters/cfn/resources/messaging.py @@ -104,10 +104,10 @@ def _list_item(p: Props, item: Any, where: str, tf_type: str) -> tuple[str | Non 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" + f"{p.owner}: '{where}' comes from a function, so the converter left it out. Add the " + f"{tf_type} by hand." ) - p.comment(f"{where.split('.', 1)[-1]} was not converted: {snippet(item)}") + p.comment(f"{where.split('.', 1)[-1]} was left out. CloudFormation value: {snippet(item)}") return None, None @@ -220,10 +220,10 @@ def subscriptions(self, b: Builder) -> 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" + f"{b.logical_id}: Subscription comes from a function, so the converter left it " + "out. Add aws_sns_topic_subscription resources by hand." ) - p.comment(f"Subscription was not converted: {snippet(subscriptions)}") + p.comment(f"Subscription was left out. CloudFormation value: {snippet(subscriptions)}") return count = sum(not b.ctx.is_no_value(s) for s in subscriptions) for index, item in enumerate(subscriptions, 1): @@ -308,10 +308,10 @@ def targets(self, b: Builder, bus: Any) -> 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" + f"{b.logical_id}: Targets comes from a function, so the converter left it out. " + "Add aws_cloudwatch_event_target resources by hand." ) - p.comment(f"Targets was not converted: {snippet(targets)}") + p.comment(f"Targets was left out. CloudFormation value: {snippet(targets)}") return suffixes = UniqueNames() for index, item in enumerate(targets, 1): @@ -576,10 +576,13 @@ def definition(self, b: Builder) -> 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" + f"{b.logical_id}: the converter cannot apply DefinitionSubstitutions to this " + "definition. Replace the ${...} placeholders by hand." + ) + p.comment( + "DefinitionSubstitutions was left out. CloudFormation value: " + f"{snippet(substitutions)}" ) - p.comment(f"DefinitionSubstitutions was not converted: {snippet(substitutions)}") def fill_logging(self, log: Props) -> None: """The logging_configuration block.""" diff --git a/services/converter-api/converters/cfn/resources/network.py b/services/converter-api/converters/cfn/resources/network.py index 2a1ad10..601d422 100644 --- a/services/converter-api/converters/cfn/resources/network.py +++ b/services/converter-api/converters/cfn/resources/network.py @@ -305,9 +305,9 @@ def convert(self, b: Builder) -> None: ) 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)" + f"{b.logical_id} routes to an instance, but the aws provider routes to its " + "network interface. Set network_interface_id = " + "aws_instance..primary_network_interface_id instead." ) @@ -419,8 +419,8 @@ def fill_dns_options(self, d: Props) -> None: 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." + "CloudFormation adds this allow-all egress rule to a group without egress rules.\n" + "Terraform removes that rule, so the converter writes it out here." ) @@ -557,8 +557,8 @@ def standalone_rules(self, b: Builder, kind: str, rules: Any, default: Any) -> N 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" + f"{b.logical_id}: the {kind} rules come from a function, so the converter cannot " + "turn them into rule resources. Add them by hand." ) return is_egress = kind == "egress" @@ -570,10 +570,12 @@ def standalone_rules(self, b: Builder, kind: str, rules: Any, default: Any) -> N 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" + f"{b.props.owner}: '{where}' comes from a function, so the converter left it " + f"out. Add the aws_vpc_security_group_{kind}_rule by hand." + ) + b.props.comment( + f"{kind}[{number - 1}] was left out. CloudFormation value: {snippet(item)}" ) - 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"))] @@ -723,16 +725,22 @@ def _key_values(p: Props, cfn_name: str) -> list[tuple[str, Any]]: 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)") + p.ctx.note( + f"{p.owner}: '{p.where}.{cfn_name}' is computed, so the converter left it out. Set " + "the attributes by hand." + ) + p.comment(f"{cfn_name} was left out because its value is 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") + p.ctx.note( + f"{p.owner}: {cfn_name} '{key}' is unknown to the converter, so it was left out. Set it " + "by hand." + ) + p.comment(f"{cfn_name} {snippet(key)} = {hcl.inline(p.ctx.expr(value))} was left out") class LoadBalancer(ResourceConverter): @@ -978,7 +986,8 @@ def add_targets(self, b: Builder) -> None: 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" + f"{b.logical_id}: Targets is computed, so the converter left it out. Attach the " + "targets by hand." ) @@ -1086,7 +1095,10 @@ def _certificate_arns(b: Builder) -> list[Any]: if certificates is None: return [] if not isinstance(certificates, list): - b.ctx.note(f"{b.logical_id}: Certificates is computed and was not converted") + b.ctx.note( + f"{b.logical_id}: Certificates is computed, so the converter left it out. Set the " + "certificates by hand." + ) return [] return [ c["CertificateArn"] for c in certificates if isinstance(c, dict) and "CertificateArn" in c @@ -1179,8 +1191,8 @@ def fill_condition(self, c: Props) -> None: 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") + c.ctx.note(f"{c.owner}: the rule condition on '{field}' was left out. Set it by hand.") + c.comment(f"The condition on {snippet(field)} was left out") return tf_name, cfn_name = self.condition_configs[field] config = c.literal(cfn_name, dict) or {} @@ -1334,7 +1346,10 @@ def convert(self, b: Builder) -> None: 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") + b.ctx.note( + f"{b.logical_id}: RecordSets is empty or computed, so the converter left it out. " + "Add the records by hand." + ) return for number, record in enumerate(records, start=1): values: dict[str, Any] = {} @@ -1420,8 +1435,9 @@ def convert(self, b: Builder) -> None: 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" + f"{b.logical_id} is validated by DNS, but the template names no 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: @@ -1486,7 +1502,10 @@ def convert(self, b: Builder) -> None: 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") + b.ctx.note( + f"{b.logical_id}: DistributionConfig is missing or computed, so the converter " + "left it out. Set it by hand." + ) return c = Props(b.ctx, config, f"{b.logical_id}.DistributionConfig", p.owner) c.boolean("enabled", "Enabled") @@ -1553,7 +1572,7 @@ def fill_origin(self, r: Props) -> None: 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" + "equivalent for S3 origins, so it was left out." ) r.block("custom_origin_config", "CustomOriginConfig", self.fill_custom_origin) r.block("origin_shield", "OriginShield", self.fill_origin_shield) @@ -1587,8 +1606,8 @@ def fill_custom_origin(self, c: Props) -> None: 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" + f"{c.owner}: '{c.where}' leaves out OriginSSLProtocols. Terraform requires them, " + "so the converter uses TLSv1.2." ) c.number("origin_read_timeout", "OriginReadTimeout") c.number("origin_keepalive_timeout", "OriginKeepaliveTimeout") diff --git a/services/converter-api/converters/cfn/resources/storage.py b/services/converter-api/converters/cfn/resources/storage.py index c8bb06d..a95d52f 100644 --- a/services/converter-api/converters/cfn/resources/storage.py +++ b/services/converter-api/converters/cfn/resources/storage.py @@ -361,9 +361,9 @@ def access_control(self, b: Builder, ownership_address: str | None) -> None: 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 " + f"{b.logical_id} sets AccessControl. S3 disables ACLs by default, so " "aws_s3_bucket_acl only works once OwnershipControls is ObjectWriter or " - "BucketOwnerPreferred" + "BucketOwnerPreferred." ) b.add_resource("aws_s3_bucket_acl", "_acl", items) diff --git a/services/converter-api/converters/cfn/sam.py b/services/converter-api/converters/cfn/sam.py index 258526f..845bd31 100644 --- a/services/converter-api/converters/cfn/sam.py +++ b/services/converter-api/converters/cfn/sam.py @@ -217,7 +217,9 @@ def __init__(self, template: dict[str, Any], notes: list[str]) -> None: 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") + raise CfnError( + "The SAM 'Globals' section must be a mapping from resource types to settings." + ) def note(self, message: str) -> None: """Add a note once.""" @@ -227,7 +229,10 @@ def note(self, message: str) -> None: 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") + self.note( + f"{logical_id}: the converter has no mapping for the SAM property '{name}' yet, " + "so it was left out. Set it by hand if you need it." + ) def add( self, @@ -272,8 +277,8 @@ def policy_template( 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" + f"{owner}: the SAM policy template '{name}' is unknown to the converter, so it " + f"was left out. Add its permissions to {role_id} by hand." ) return [] return template(params if isinstance(params, dict) else {}) @@ -306,7 +311,10 @@ def role( ((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}") + self.exp.note( + f"{owner}: a Policies entry has a form the converter cannot read, so it was " + f"left out. Add it to {role_id} by hand." + ) if statements: inline.append(inline_policy(f"{role_id}PolicyTemplates", statements)) role: dict[str, Any] = { @@ -484,8 +492,8 @@ def expand(self, logical_id: str, resource: dict[str, Any]) -> None: 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" + f"{logical_id} sets both Role and Policies. SAM ignores Policies in that " + "case, so the converter leaves them out too." ) self.exp.add(logical_id, "AWS::Lambda::Function", fn, resource, meta(resource)) @@ -493,12 +501,14 @@ def expand(self, logical_id: str, resource: dict[str, Any]) -> None: 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") + raise CfnError( + f"The 'Events' of '{logical_id}' must be a mapping from event names to events." + ) 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" + f"The event '{event_name}' of '{logical_id}' must be a mapping with a Type " + "and Properties." ) managed.extend(self.event(f"{logical_id}{event_name}", event, target, resource)) if isinstance(url, dict): @@ -521,7 +531,8 @@ def expand(self, logical_id: str, resource: dict[str, Any]) -> None: 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" + f"{logical_id}: the converter leaves out the SAM setting {name}. Set it up by " + "hand." ) p.pop("Metadata", None) self.exp.leftovers(logical_id, p) @@ -546,7 +557,10 @@ def code(self, logical_id: str, p: dict[str, Any], fn: dict[str, Any]) -> None: 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") + self.exp.note( + f"{logical_id}: CodeUri comes from a function, so the converter left it out. Set " + "the function code by hand." + ) 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.""" @@ -638,8 +652,8 @@ def event( 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" + f"{event_id}: the SAM event type '{kind}' was left out. Connect the event source " + "to the function by hand." ) return [] @@ -676,8 +690,8 @@ def sns_event( 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" + f"{event_id}: the SqsSubscription of the SNS event was left out. Add the queue " + "between the topic and the function by hand." ) self.exp.add(event_id, "AWS::SNS::Subscription", subscription, origin) self.iam.permission( @@ -695,8 +709,8 @@ def s3_event( 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" + f"{event_id}: the bucket of the S3 event lives outside this template. Add the " + "notification to that bucket by hand." ) return config: dict[str, Any] = {"Function": target} @@ -739,8 +753,8 @@ def api_event( } if props.get("Auth"): self.exp.note( - f"{event_id}: the Auth setting of the API event was not converted; add the " - "authorizer" + f"{event_id}: the Auth setting of the API event was left out. Add the authorizer " + "by hand." ) if http and path == "$default": scope = "*" @@ -853,8 +867,8 @@ def rest_api(self, logical_id: str, resource: dict[str, Any] | None) -> None: ): 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" + f"{logical_id}: the SAM API setting '{name}' was left out. Add it to the API " + "definition by hand." ) self.exp.leftovers(logical_id, p) @@ -877,7 +891,8 @@ def http_api(self, logical_id: str, resource: dict[str, Any] | None) -> None: api["CorsConfiguration"] = cors elif cors is not None: self.exp.note( - f"{logical_id}: CorsConfiguration given as a single value was not converted" + f"{logical_id}: CorsConfiguration is a single value, so it was left out. Write it " + "as a mapping or set up CORS by hand." ) for name in ("Description", "DisableExecuteApiEndpoint", "FailOnWarnings"): if name in p: @@ -909,8 +924,8 @@ def http_api(self, logical_id: str, resource: dict[str, Any] | None) -> None: 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" + f"{logical_id}: the SAM HTTP API setting '{name}' was left out. Set it up by " + "hand." ) self.exp.leftovers(logical_id, p) @@ -1000,8 +1015,8 @@ def expand(self, logical_id: str, resource: dict[str, Any]) -> None: 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()" + f"{logical_id}: DefinitionSubstitutions cannot be applied to a definition " + "file, so they were left out. Use templatefile() in place of file()." ) elif uri is not None: machine["DefinitionS3Location"] = s3_location(uri) @@ -1067,7 +1082,10 @@ def event( 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") + self.exp.note( + f"{event_id}: the SAM state machine event type '{kind}' was left out. Connect the " + "event source by hand." + ) # --- connectors ------------------------------------------------------------------------- @@ -1093,8 +1111,8 @@ def expand(self, logical_id: str, props: dict[str, Any], source_id: str | None) 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" + f"{logical_id}: one end of the connector lives outside this template, so the " + "connector was left out. Grant the access by hand." ) continue self.connect(logical_id, source_id, destination_id or "", permissions, name) @@ -1126,8 +1144,8 @@ def connect( 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" + f"{logical_id}: the connector from {source_type} to {destination_type} was left " + "out. Grant the access by hand." ) return if destination_type in REF_IS_ARN: @@ -1229,8 +1247,8 @@ def expand_resources( 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" + f"{logical_id} ({kind}) is a SAM type the converter cannot expand yet, so it " + "was left out. Convert it by hand." ) else: self.exp.out[logical_id] = resource diff --git a/services/converter-api/tests/test_cfn_apigateway.py b/services/converter-api/tests/test_cfn_apigateway.py index 821513b..fe32ef1 100644 --- a/services/converter-api/tests/test_cfn_apigateway.py +++ b/services/converter-api/tests/test_cfn_apigateway.py @@ -23,7 +23,7 @@ def convert(resources: dict) -> tuple[str, list[str]]: 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] + assert not [n for n in result["notes"] if "was left out" 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 @@ -73,8 +73,8 @@ def test_rest_api_defaults_and_body_location(): ) 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) + assert any("Api: BodyS3Location was left out" in n for n in notes) + assert any("NoBody: the template leaves out Name" in n for n in notes) def test_deployment_triggers_only_for_apis_with_a_body(): @@ -94,7 +94,7 @@ def test_deployment_triggers_only_for_apis_with_a_body(): } ) assert "triggers" not in main - assert sum("only redeployed when its arguments change" in n for n in notes) == 3 + assert sum("only redeploys a deployment when its arguments change" in n for n in notes) == 3 assert 'stage_name = "dev"' in main @@ -113,8 +113,8 @@ def test_stage_method_settings_with_computed_path(): ) 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) + assert any("MethodSettings[0] computes its path or method" in n for n in notes) + assert any("'Stage.MethodSettings[0].Odd' yet" in n for n in notes) def test_method_without_integration_and_unmatched_responses(): @@ -250,8 +250,8 @@ def test_conditional_and_computed_method_settings(): assert "count = local.on ? 1 : 0" in main assert "metrics_enabled = true" in main assert main.count('resource "aws_api_gateway_method_settings"') == 1 - assert main.count("# MethodSettings was not converted") == 2 - assert len([n for n in notes if "is computed by a function" in n]) == 2 + assert main.count("# MethodSettings was left out") == 2 + assert len([n for n in notes if "comes from a function" in n]) == 2 def test_conditional_and_computed_method_responses_and_integration(): @@ -298,9 +298,9 @@ def test_conditional_and_computed_method_responses_and_integration(): only = main.split('"get_integration_response_200"')[1] assert only.lstrip("{\n ").startswith("count = local.on ? 1 : 0") assert "aws_api_gateway_method_response.get_response_500," in main - assert "# MethodResponses was not converted" in main - assert "# Integration was not converted" in main - assert "# Integration.IntegrationResponses was not converted" in main + assert "# MethodResponses was left out" in main + assert "# Integration was left out" in main + assert "# Integration.IntegrationResponses was left out" in main assert "computed_integration" not in main @@ -352,11 +352,11 @@ def test_conditional_and_computed_route_parameters_and_settings(): assert 'dynamic "request_parameter" {\n for_each = local.on ? [1] : []' in main assert '"route.request.querystring.c"\n required = true' in main assert 'Fn::If"\n' not in main and 'request_parameter_key = "Fn::If"' not in main - assert "# RequestParameters.route.request.querystring.b was not converted" in main - assert "# RequestParameters was not converted" in main + assert "# RequestParameters.route.request.querystring.b was left out" in main + assert "# RequestParameters was left out" in main assert 'dynamic "route_settings" {\n for_each = local.on ? [1] : []' in main - assert "# RouteSettings.GET /x was not converted" in main - assert "# RouteSettings was not converted" in main + assert "# RouteSettings.GET /x was left out" in main + assert "# RouteSettings was left out" in main assert 'route_key = "Fn::If"' not in main @@ -420,4 +420,4 @@ def test_http_integration_tls_config(): } ) assert 'tls_config {\n server_name_to_verify = "example.com"\n }' in main - assert not [n for n in notes if "was not converted" in n] + assert not [n for n in notes if "was left out" in n] diff --git a/services/converter-api/tests/test_cfn_cdk.py b/services/converter-api/tests/test_cfn_cdk.py index d848638..3909682 100644 --- a/services/converter-api/tests/test_cfn_cdk.py +++ b/services/converter-api/tests/test_cfn_cdk.py @@ -154,7 +154,7 @@ def test_auto_delete_with_an_external_bucket_and_kept_conditions(): 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"]) + assert any("The Rules section of the template was left out" in n for n in result["notes"]) def test_unused_cdk_condition_is_removed_and_empty_policy_dropped(): diff --git a/services/converter-api/tests/test_cfn_compute.py b/services/converter-api/tests/test_cfn_compute.py index ab7acac..719f069 100644 --- a/services/converter-api/tests/test_cfn_compute.py +++ b/services/converter-api/tests/test_cfn_compute.py @@ -42,7 +42,7 @@ def with_hints(resources: dict, hints: dict) -> tuple[str, bool]: 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] + assert not [n for n in result["notes"] if "was left out" 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 @@ -133,12 +133,12 @@ def test_function_without_code_and_image_with_explicit_package_type(): 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) + assert any("NoCode: the template leaves out 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) + assert any("'Fn.Code.Odd' yet" in n for n in notes) def test_versions_of_other_functions_do_not_publish(): @@ -256,9 +256,9 @@ def test_instance_devices_interfaces_and_user_data(): 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) + assert any("'Vm.BlockDeviceMappings.Odd' yet" 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) + assert any(f"'{name}.NetworkInterfaces' yet" in n for n in notes) def test_launch_template_without_data(): @@ -518,7 +518,7 @@ def test_primary_interface_kept_on_termination_is_noted(): }, } ) - assert '# DeleteOnTermination was not converted: "false"' in main + assert '# DeleteOnTermination was left out. CloudFormation value: "false"' in main assert sum("primary network interface" in n for n in notes) == 1 @@ -590,7 +590,7 @@ def test_conditional_container_is_filtered_out_of_the_list(): 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 + assert "# Host was left out" in main def test_namespace_name_is_noted(): @@ -660,8 +660,8 @@ def test_conditional_alias_routing_and_concurrency(): 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 + assert "# AdditionalVersionWeights was left out" in main + assert "# ProvisionedConcurrencyConfig was left out" in main def test_conditional_and_computed_block_device_mappings(): @@ -686,9 +686,9 @@ def test_conditional_and_computed_block_device_mappings(): ) 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 "# BlockDeviceMappings was left out" 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) + assert any("'Whole.BlockDeviceMappings' comes from a function" in n for n in notes) def test_computed_launch_template_tag_specifications_do_not_crash(): @@ -716,8 +716,8 @@ def test_computed_launch_template_tag_specifications_do_not_crash(): }, ) 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 + assert "# TagSpecifications.Tags was left out" in main + assert len([n for n in notes if "comes from a function" in n]) == 3 EVIL = 'x" ${file("/etc/passwd")} y' @@ -817,4 +817,4 @@ def test_file_systems_launch_templates_credits_and_placement(): assert 'launch_template {\n name = "lt"\n version = "1"\n }' in main assert 'cpu_credits = "unlimited"' in main assert 'availability_zone = "eu-west-1a"' in main and 'tenancy = "dedicated"' in main - assert not [n for n in notes if "was not converted" in n] + assert not [n for n in notes if "was left out" in n] diff --git a/services/converter-api/tests/test_cfn_core.py b/services/converter-api/tests/test_cfn_core.py index 6103b10..cfd356e 100644 --- a/services/converter-api/tests/test_cfn_core.py +++ b/services/converter-api/tests/test_cfn_core.py @@ -120,19 +120,23 @@ def test_json_templates_and_bom(): @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), + ("", "The template is empty", None), + (" ", "The template is empty", None), + ('{"Resources": ', "The JSON has a syntax error", 1), + ("\n\n{\n bad", "The JSON has a syntax error", 4), + ("Resources: [1\n", "The YAML has a syntax error", 2), + ("Resources:\n B: !Unknown x\n", "The YAML tag '!Unknown' is unknown", 2), + ("- 1\n- 2\n", "top level of the template must be a mapping", None), + ("Description: x\n", "needs a 'Resources' section", None), + ("Resources: [1]\n", "'Resources' section 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: {Properties: {}}\n", "resource 'B' needs a '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: [1]\n", + "'Parameters' section 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), ], @@ -147,14 +151,14 @@ def test_invalid_templates(text, message, 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"): + with pytest.raises(CfnError, match="too deeply"): load_template("Resources: " + "[" * 150 + "]" * 150) - with pytest.raises(CfnError, match="nested too deeply"): + with pytest.raises(CfnError, match="too deeply"): load_template('{"Resources": ' + "[" * 150 + "]" * 150 + "}") - with pytest.raises(CfnError, match="nested too deeply"): + with pytest.raises(CfnError, match="too deeply"): load_template('{"Resources": ' + "[" * 100_000 + "]" * 100_000 + "}") values = ",".join("0" * 100_001) - with pytest.raises(CfnError, match="Template too large"): + with pytest.raises(CfnError, match="The template has more than"): 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 + "]}}}") @@ -165,7 +169,7 @@ def test_alias_bombs_are_rejected(): 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"): + with pytest.raises(CfnError, match="The template has more than"): load_template(bomb + "Resources: {B: {Type: X, Properties: {V: *a7}}}\n") @@ -343,7 +347,9 @@ def test_get_att_unknown_attribute_on_a_mapped_type_is_noted(): } 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)) + assert any( + "Check in the Terraform docs that this attribute exists" in n for n in notes(template) + ) def test_get_att_computed_attribute_name(): @@ -353,24 +359,27 @@ def test_get_att_computed_attribute_name(): "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)) + assert any("builds its attribute name at deploy time" 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]"), + ({"Ref": "Nope"}, "the template has no parameter or resource with that name"), + ({"Ref": ["x"]}, "needs the name of a parameter or resource"), + ({"Fn::GetAtt": ["Nope", "Arn"]}, "points to 'Nope', but the template has no resource"), + ({"Fn::GetAtt": ["Bucket"]}, "needs a resource and an 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::Sub": ["a", "b"]}, "needs a string or a [string, {variables}] pair"), + ({"Fn::Join": ["a"]}, "'Fn::Join' needs a list of 2"), + ({"Fn::Select": [5, ["a"]]}, "past the end of the list"), + ({"Fn::If": ["Nope", 1, 2]}, "uses the condition 'Nope', but Conditions has no entry"), + ( + {"Fn::FindInMap": ["Nope", "a", "b"]}, + "points to the mapping 'Nope', but the template has no mapping", + ), ({"Fn::And": [{"Condition": "X"}]}, "2 to 10 conditions"), - ({"Fn::Cidr": ["not-a-cidr", 2, 8]}, "is unable to split"), + ({"Fn::Cidr": ["not-a-cidr", 2, 8]}, "cannot split"), ], ) def test_invalid_intrinsics(value, message): @@ -467,7 +476,7 @@ def test_import_value_becomes_a_variable(): 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)) + assert any("Terraform has no exports of its own" in n for n in notes(template)) computed = {"Fn::ImportValue": {"Fn::Sub": "${AWS::StackName}-Vpc"}} assert expression(computed).startswith("var.import_") @@ -480,7 +489,7 @@ def test_language_extensions_and_unsupported_functions(): 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)) + assert any("'Fn::Nope' has no Terraform conversion" in n for n in notes(unknown)) def test_plain_mappings_and_lists_keep_their_keys(): @@ -493,7 +502,7 @@ 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"): + with pytest.raises(CfnError, match="too deeply"): expression(value) @@ -564,7 +573,7 @@ def test_parameters_become_variables_with_validation(): 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 'description = "Image (the 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 @@ -614,7 +623,7 @@ def test_resource_attributes(): 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 "# C (Custom::Thing) was left out" in main assert 'variable "c_result"' in out["variables.tf"] assert "value = var.c\n" in out["outputs.tf"] messages = "\n".join(notes(template)) @@ -622,16 +631,16 @@ def test_resource_attributes(): "prevent_destroy", "Terraform takes no snapshot", "UpdateReplacePolicy Retain", - "has a CreationPolicy", + "CreationPolicy only works in CloudFormation", "cfn-init", - "custom resources run a Lambda function", + "Custom resources call 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'"): + with pytest.raises(CfnError, match="has DependsOn 'Nope', but the template has no resource"): files(template) @@ -645,8 +654,8 @@ def test_unsupported_types(): 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 "This type only exists inside CloudFormation" in messages + assert "Neither the aws mappings nor the awscc provider covers this type" in messages assert [r["address"] for r in result["resources"]] == [None, None] @@ -664,16 +673,16 @@ def test_leftover_properties_are_kept_as_comments_and_noted(): } } main = files(template)["main.tf"] - assert '# Unknown was not converted: {"a": "bbb' in main and "bbb...\n" in main + assert '# Unknown was left out. CloudFormation value: {"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)) + assert any("no mapping for 'B.Unknown' yet" 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)) + assert any("the template leaves out TableName" in n for n in notes(template)) # --- awscc ------------------------------------------------------------------------------ @@ -727,7 +736,7 @@ def test_awscc_conversion_follows_the_schema_index(): 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"]) + assert any("because you chose the awscc provider" in n for n in result["notes"]) def test_awscc_only_template_has_no_aws_provider(): @@ -768,9 +777,9 @@ def test_import_blocks(): }, } imports = files(template, {"include_imports": True})["imports.tf"] - assert "# Adopt the resources the stack created" in imports + assert "# These import blocks adopt the resources the stack already 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 = aws_s3_bucket.unnamed[0]\n id = "TODO: the 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 @@ -804,23 +813,23 @@ def test_template_level_notes(): "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 "The top-level section 'Extra' is unknown" in messages + assert "The transform 'AWS::SecretsManager-2020-07-23'" in messages + assert "The transform 'AWS::Include'" in messages + assert "The Rules section of the template was left out" in messages assert "LanguageExtensions" not in messages def test_invalid_options(): - with pytest.raises(CfnError, match="Unknown provider"): + with pytest.raises(CfnError, match="The provider 'google' is unknown"): convert_template("Resources: {}", "google") - with pytest.raises(CfnError, match="Unknown layout"): + with pytest.raises(CfnError, match="The layout 'tree' is unknown"): convert_template("Resources: {}", "aws", "tree") - with pytest.raises(CfnError, match="Unknown provider"): + with pytest.raises(CfnError, match="The provider 'google' is unknown"): Converter({"Resources": {}}, provider="google") converter = Converter({"Resources": BUCKET}) - with pytest.raises(CfnError, match="Unknown layout"): + with pytest.raises(CfnError, match="The layout 'tree' is unknown"): converter.files("tree") @@ -872,12 +881,12 @@ def test_awscc_renamed_types_missing_properties_and_local_code(): 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 "the awscc provider reads Lambda code only from S3" in messages + assert "# DeliveryPolicy was left out" in main + assert "# DeletionProtectionEnabled was left out" in main assert ( - "'Glue.FederatedCatalog.ConnectionType' is missing from awscc_glue_catalog in this " - "provider version" in messages + "awscc_glue_catalog in this awscc provider version has no argument for " + "'Glue.FederatedCatalog.ConnectionType'" in messages ) @@ -909,11 +918,11 @@ def test_blocks_from_computed_values(): 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 "# Text was left out" in rendered + assert "# Short was left out" 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 + assert "# Both was left out" in rendered + assert sum("comes from a function" in n for n in ctx.notes) == 3 def test_json_values_and_template_parts(): @@ -995,7 +1004,7 @@ def test_optional_items_and_literal_guard(): 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 + assert sum("comes from 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"}) diff --git a/services/converter-api/tests/test_cfn_data.py b/services/converter-api/tests/test_cfn_data.py index 6de2c19..4884c7b 100644 --- a/services/converter-api/tests/test_cfn_data.py +++ b/services/converter-api/tests/test_cfn_data.py @@ -107,7 +107,7 @@ def test_parameter_group_values(): 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) + assert any("Computed.Parameters' yet" in n for n in notes) def test_cluster_attributes_and_password(): @@ -167,8 +167,10 @@ def test_secret_with_generated_value_is_reported(): }, 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 "GenerateSecretString was left out" in main + assert any( + "random_password and secret_string_wo. You can also 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 @@ -280,7 +282,7 @@ def test_cluster_member_instance_is_a_cluster_instance(): 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) + assert not any("left out" 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 @@ -302,4 +304,4 @@ def test_parameter_group_applies_parameters_the_default_way(): 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) + assert any('Set 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 index e202dd7..6a44c4c 100644 --- a/services/converter-api/tests/test_cfn_iam.py +++ b/services/converter-api/tests/test_cfn_iam.py @@ -49,7 +49,7 @@ def convert( @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 not [n for n in result["notes"] if "left out" in n] assert result["summary"]["awscc"] == 0 and result["summary"]["unsupported"] == 0 @@ -95,7 +95,7 @@ def test_role_with_inline_and_managed_policies(): 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] + assert not [n for n in notes if "left out" in n] def test_role_policies_computed_by_functions_are_reported(): @@ -113,10 +113,10 @@ def test_role_policies_computed_by_functions_are_reported(): }, 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 "Policies[0] was left out" in main + assert "ManagedPolicyArns was left out" in main + assert any("inline policy 1 comes from a function" in n for n in notes) + assert any("ManagedPolicyArns comes from a function" in n for n in notes) assert "count = local.on ? 1 : 0" in main @@ -158,7 +158,7 @@ def test_policy_attached_to_roles_users_and_groups(): 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] + assert not [n for n in notes if "left out" in n] def test_policy_type_follows_the_first_principal(): @@ -190,9 +190,9 @@ def test_policy_without_readable_principals_gets_a_variable(): ) assert 'resource "aws_iam_role_policy" "policy"' in main assert "role = var.policy_role" in main - assert "Roles was not converted" in main + assert "Roles was left out" in main assert 'variable "policy_role"' in files["variables.tf"] - assert any("lists no role, user or group" in n for n in notes) + assert any("names no role, user or group" in n for n in notes) def test_managed_policy_and_attachments(): @@ -230,7 +230,7 @@ def test_instance_profile_takes_its_one_role(): 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 any("Two.Roles' yet" in n for n in notes) assert "aws_iam_instance_profile.profile.arn" in files["outputs.tf"] @@ -263,8 +263,8 @@ def test_user_and_group(): 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) + assert any("User.LoginProfile' yet" in n for n in notes) + assert any("Group: the template leaves out GroupName" in n for n in notes) def squash(text: str) -> str: @@ -314,7 +314,7 @@ def test_optional_managed_policies_and_inline_policies_are_counted(): 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) + assert not any("left out" in n or "computed by a function" in n for n in notes) def test_policy_with_optional_principals(): diff --git a/services/converter-api/tests/test_cfn_messaging.py b/services/converter-api/tests/test_cfn_messaging.py index ed49aad..08dad8b 100644 --- a/services/converter-api/tests/test_cfn_messaging.py +++ b/services/converter-api/tests/test_cfn_messaging.py @@ -68,8 +68,8 @@ def test_queue_policy_for_several_queues_and_a_computed_list(): 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) + assert "Queues was left out" in main + assert any("Computed.Queues' yet" in n for n in notes) def test_topic_subscriptions(): @@ -95,8 +95,8 @@ def test_topic_subscriptions(): ) 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 "Subscription was left out" in main + assert any("Computed: Subscription comes from a function" 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 @@ -214,7 +214,7 @@ def test_rule_targets_of_every_kind(): 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 any("Computed: Targets comes from a function" in n for n in notes) assert not [n for n in notes if "property" in n] @@ -227,7 +227,7 @@ def test_event_bus_without_policy_and_plain_stream(): ) 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) + assert any("Stream: the template leaves out Name" in n for n in notes) def _machine(props: dict) -> dict: @@ -262,7 +262,7 @@ def test_definition_substitutions_on_an_object(): 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] + assert notes == [] or not [n for n in notes if "left out" in n] def test_definition_string_forms(): @@ -304,7 +304,7 @@ def test_definition_string_forms(): ) 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 any("Bad: the converter cannot apply DefinitionSubstitutions" 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 @@ -503,10 +503,10 @@ def test_optional_subscriptions_and_rule_targets_are_counted(): 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) + assert "Subscription[2] was left out" in main + assert "Targets[2] was left out" in main + assert any("'Topic.Subscription[2]' comes from a function" in n for n in notes) + assert any("'Rule.Targets[2]' comes from a function" in n for n in notes) def _ecs_rule(network: object) -> dict: @@ -549,9 +549,9 @@ def test_ecs_target_network_configuration_from_functions(): ) 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 "NetworkConfiguration was left out" in main + assert "AwsVpcConfiguration was left out" in main + assert "ArrayProperties was left out" 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) diff --git a/services/converter-api/tests/test_cfn_network.py b/services/converter-api/tests/test_cfn_network.py index dfbe67a..0bdc4a2 100644 --- a/services/converter-api/tests/test_cfn_network.py +++ b/services/converter-api/tests/test_cfn_network.py @@ -239,7 +239,7 @@ def test_group_with_standalone_rules_gets_rule_resources(): 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 + "Other: the ingress rules come from a function, so the converter cannot turn them" in n for n in notes ) assert "ip_protocol = var.proto" in hcl @@ -495,7 +495,7 @@ def test_listener_rule_conditions(): 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) + assert any("rule condition on 'made-up' was left out" in n for n in notes) # --- Route 53 ----------------------------------------------------------------------------- @@ -643,7 +643,9 @@ def test_certificate_validation_variants(): ) 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 any( + "NoZone is validated by DNS, but the template names no 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 @@ -756,11 +758,11 @@ def test_distribution_full_config(): '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 any("OriginReadTimeout' has no Terraform equivalent for S3 origins" 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 any("leaves out 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 @@ -886,8 +888,8 @@ def test_standalone_rules_from_optional_items_are_counted(): ) 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) + assert "ingress[2] was left out" in hcl + assert any("'Sg.ingress[2]' comes from a function" in n for n in notes) def test_default_egress_kept_when_the_egress_rules_are_optional(): @@ -921,7 +923,7 @@ def test_default_egress_kept_when_the_egress_rules_are_optional(): 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 "Egress was left out" 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 " @@ -929,12 +931,12 @@ def test_default_egress_kept_when_the_egress_rules_are_optional(): ) 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 = " + "? 1 : 0 # CloudFormation adds this allow-all egress rule to a group without egress rules. " + "# Terraform removes that rule, so the converter writes it out here. 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) + assert any("Computed.Egress' comes from a function" in n for n in notes) + assert any("Odd.Egress' comes from a function" in n for n in notes) def _target_group(attributes: list, props: dict | None = None) -> dict: @@ -968,8 +970,13 @@ def test_target_group_stickiness_defaults_and_cookie_durations(): '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) + assert ( + 'TargetGroupAttributes "stickiness.lb_cookie.duration_seconds" = "3600" was left out' in hcl + ) + assert any( + "TargetGroupAttributes 'stickiness.lb_cookie.duration_seconds' is unknown" in n + for n in notes + ) def test_partial_health_check_gets_the_aws_thresholds(): @@ -1135,16 +1142,16 @@ def test_lists_from_functions_do_not_crash(): 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", + "FunctionAssociations was left out", + "S3OriginConfig was left out", + "StatusCodes was left out", + "Members.Items was left out", + "Values was left out", + "HostHeaderConfig was left out", + "TargetGroups was left out", ): assert text in hcl - assert any("computed by a function" in n for n in notes) + assert any("comes from a function" in n for n in notes) def test_distribution_http_version_and_zone_comment_defaults(): diff --git a/services/converter-api/tests/test_cfn_observability.py b/services/converter-api/tests/test_cfn_observability.py index d6d06ca..ce72255 100644 --- a/services/converter-api/tests/test_cfn_observability.py +++ b/services/converter-api/tests/test_cfn_observability.py @@ -78,7 +78,7 @@ def test_metric_filter_values_and_dimensions(): 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] + assert not [n for n in notes if "left out" in n] def test_subscription_filter(): @@ -97,7 +97,7 @@ def test_subscription_filter(): ) 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) + assert any("Sub: the template leaves out FilterName" in n for n in notes) def test_alarm_metric_queries_and_dimension_maps(): @@ -218,7 +218,7 @@ def test_alarm_metric_stat_from_a_function_is_reported(): }, 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) + assert "MetricStat was left out" in main + assert "Metric was left out" in main + assert any("Alarm.Metrics[0].MetricStat' comes from a function" in n for n in notes) + assert any("Alarm.Metrics[1].MetricStat.Metric' comes from a function" 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 index 2a3cad8..2259153 100644 --- a/services/converter-api/tests/test_cfn_review_fixes.py +++ b/services/converter-api/tests/test_cfn_review_fixes.py @@ -59,7 +59,7 @@ def test_names_must_be_alphanumeric(section, name): "Outputs": {"Value": "x"}, }[section] template.setdefault(section, {})[name] = entry - with pytest.raises(CfnError, match="letters and digits only"): + with pytest.raises(CfnError, match="can only use letters and digits"): load_template(json.dumps(template)) @@ -87,9 +87,9 @@ def test_sam_definition_uri_is_escaped(): def test_non_finite_numbers_and_huge_cidr_counts_are_rejected(): - with pytest.raises(CfnError, match="Invalid number"): + with pytest.raises(CfnError, match="infinite or undefined"): load_template("Resources: {B: {Type: X, Properties: {V: 1.0e400}}}") - with pytest.raises(CfnError, match="Invalid number"): + with pytest.raises(CfnError, match="infinite or undefined"): 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]}) @@ -104,7 +104,7 @@ def test_many_colliding_names_stay_linear(): 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"): + with pytest.raises(CfnError, match="too deeply"): ctx.json("[" * 150 + "]" * 150) diff --git a/services/converter-api/tests/test_cfn_sam.py b/services/converter-api/tests/test_cfn_sam.py index acc27ec..8b51607 100644 --- a/services/converter-api/tests/test_cfn_sam.py +++ b/services/converter-api/tests/test_cfn_sam.py @@ -41,7 +41,7 @@ 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] + assert not [n for n in result["notes"] if "was left out" in n] def test_function_role_and_globals(): @@ -82,7 +82,7 @@ def test_function_role_and_globals(): 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 + assert any("SAM property 'Unknown' yet" in n for n in notes) @pytest.mark.parametrize( @@ -108,7 +108,7 @@ def test_code_locations(props, code, 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) + assert any("CodeUri comes from a function" in n for n in notes) def test_dead_letter_queue_and_role_options(): @@ -174,8 +174,8 @@ def test_policies(): 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) + assert any("the SAM policy template 'NoSuchTemplate' is unknown" in n for n in notes) + assert any("a Policies entry has a form the converter cannot read" in n for n in notes) @pytest.mark.parametrize("name", PolicyTemplates().names()) @@ -325,7 +325,7 @@ def test_sns_s3_and_logs_events(): 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 + "FnElsewhere: the bucket of the S3 event lives outside this template" in n for n in notes ) @@ -424,9 +424,9 @@ def test_api_events_build_the_rest_api_body(): 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) + assert any("Auth setting of the API event was left out" in n for n in notes) + assert any("MyApi: the SAM API setting 'Cors'" in n for n in notes) + assert any("MyApi: the converter has no mapping for the SAM property 'Odd'" in n for n in notes) def test_http_api_events(): @@ -498,10 +498,10 @@ def test_http_api_events(): ) 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) + assert any("CorsConfiguration is a single value" in n for n in notes) + assert any("Http: the SAM HTTP API setting 'Auth'" in n for n in notes) + assert any("Http: the converter has no mapping for the SAM property 'Odd'" in n for n in notes) + assert any("FnPost: the Auth setting of the API event was left out" in n for n in notes) def test_url_alias_and_unconverted_function_settings(): @@ -545,8 +545,8 @@ def test_url_alias_and_unconverted_function_settings(): "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) + assert any("the converter leaves out the SAM setting DeploymentPreference" in n for n in notes) + assert any("the SAM event type 'IoTRule' was left out" in n for n in notes) @pytest.mark.parametrize( @@ -559,7 +559,7 @@ def test_url_alias_and_unconverted_function_settings(): def test_invalid_sam(resources, message): with pytest.raises(CfnError, match=message): expand(resources) - with pytest.raises(CfnError, match="'Globals' must be a mapping"): + with pytest.raises(CfnError, match="'Globals' section must be a mapping"): expand({"Fn": function()}, {"Globals": [1]}) @@ -612,9 +612,11 @@ def test_simple_table_layer_and_other_types(): 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) + assert any("App (AWS::Serverless::Application) is a SAM type" in n for n in notes) + assert any( + "Custom: the converter has no mapping for the SAM property 'Odd'" in n for n in notes + ) + assert any("UriLayer: the converter has no mapping for the SAM property" in n for n in notes) def test_state_machines(): @@ -694,9 +696,12 @@ def test_state_machines(): 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) + assert any("FlowHttp: the SAM state machine event type 'Api'" in n for n in notes) + assert any( + "FromFile: DefinitionSubstitutions cannot be applied to a definition file" in n + for n in notes + ) + assert any("Flow: the converter has no mapping for the SAM property 'Odd'" in n for n in notes) def test_connectors(): @@ -799,12 +804,13 @@ def test_connectors(): 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("FnToMany: one end of the connector lives 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 + "QueueToTopic: the 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 + "FnToNothing: the connector from AWS::Lambda::Function to AWS::SNS::Topic" in n + for n in notes ) diff --git a/services/converter-api/tests/test_cfn_storage.py b/services/converter-api/tests/test_cfn_storage.py index f576492..b445d00 100644 --- a/services/converter-api/tests/test_cfn_storage.py +++ b/services/converter-api/tests/test_cfn_storage.py @@ -29,7 +29,7 @@ def convert(resources: dict, extra: dict | None = None) -> tuple[str, list[str]] 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] + assert not [n for n in result["notes"] if "was left out" 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 @@ -200,8 +200,11 @@ def test_dynamodb_table_with_only_a_hash_key_and_no_stream(): } ) 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 ( + 'local_secondary_index {\n name = "l"\n' + ' # Projection was left out. CloudFormation value: "x"\n }' in main + ) + assert '# KeySchema was left out. CloudFormation value: "computed"' in main assert not any("TableName" in n for n in notes) @@ -365,9 +368,12 @@ def test_conditional_stream_and_stream_policy_is_reported(): assert "stream_enabled = local.on" in main assert 'stream_view_type = local.on ? "KEYS_ONLY" : null' in main assert "stream_view_type = null" not in main - assert '# ResourcePolicy was not converted: {"P": 1}' in main - assert any("'Policy.StreamSpecification.ResourcePolicy' was not converted" in n for n in notes) - assert "# StreamSpecification was not converted" in main + assert '# ResourcePolicy was left out. CloudFormation value: {"P": 1}' in main + assert any( + "'Policy.StreamSpecification.ResourcePolicy' yet" in n + for n in notes + ) + assert "# StreamSpecification was left out" in main def test_contributor_insights_of_an_index_is_reported(): @@ -387,7 +393,7 @@ def test_contributor_insights_of_an_index_is_reported(): ) } ) - assert "# ContributorInsightsSpecification was not converted" in main + assert "# ContributorInsightsSpecification was left out" in main assert any("GlobalSecondaryIndexes[0].ContributorInsightsSpecification" in n for n in notes) @@ -424,10 +430,10 @@ def test_computed_table_structures_are_reported_not_guessed(): ) assert 'dynamic "attribute" {\n for_each = local.on ? [1] : []' in main assert 'name = "gk"' in main - assert main.count("# AttributeDefinitions was not converted") == 2 - assert main.count("# KeySchema was not converted") == 3 - assert "# ProvisionedThroughput was not converted" in main - assert "# Projection was not converted" in main + assert main.count("# AttributeDefinitions was left out") == 2 + assert main.count("# KeySchema was left out") == 3 + assert "# ProvisionedThroughput was left out" in main + assert "# Projection was left out" in main assert 'projection_type = "ALL"' not in main @@ -469,9 +475,9 @@ def test_lifecycle_rule_with_conditional_and_computed_parts(): assert "noncurrent_days = null" not in main assert 'tag {\n key = "a"' in main for name in ("Transitions", "TagFilters"): - assert main.count(f"# {name} was not converted") == 2 - assert "# NoncurrentVersionExpiration was not converted" in main - assert "# AbortIncompleteMultipartUpload was not converted" in main + assert main.count(f"# {name} was left out") == 2 + assert "# NoncurrentVersionExpiration was left out" in main + assert "# AbortIncompleteMultipartUpload was left out" in main def test_more_than_a_thousand_lifecycle_rules(): @@ -537,12 +543,12 @@ def test_conditional_and_computed_notification_parts(): }, CONDITION, ) - assert "# Filter.S3Key.Rules was not converted" in main + assert "# Filter.S3Key.Rules was left out" in main assert 'filter_suffix = ".x"' in main - assert "# Filter.S3Key was not converted" in main + assert "# Filter.S3Key was left out" in main assert "eventbridge = local.on ? true : false" in main assert "eventbridge = true" in main - assert "# EventBridgeConfiguration was not converted" in main + assert "# EventBridgeConfiguration was left out" in main def test_conditional_and_computed_ecr_lifecycle_policy(): @@ -575,9 +581,11 @@ def test_conditional_and_computed_ecr_lifecycle_policy(): ) lifecycle = main.split('resource "aws_ecr_lifecycle_policy" "cond_lifecycle"')[1] assert lifecycle.startswith(" {\n count = local.on ? 1 : 0") - assert main.count('# RegistryId was not converted: "1"') == 2 - assert any("'Registry.LifecyclePolicy.RegistryId' was not converted" in n for n in notes) - assert "# LifecyclePolicy was not converted" in main + assert main.count('# RegistryId was left out. CloudFormation value: "1"') == 2 + assert any( + "'Registry.LifecyclePolicy.RegistryId' yet" in n for n in notes + ) + assert "# LifecyclePolicy was left out" in main def test_storage_template_text_cannot_inject_hcl(): diff --git a/services/web/tests/test_examples.py b/services/web/tests/test_examples.py index f7d5a82..d4a273b 100644 --- a/services/web/tests/test_examples.py +++ b/services/web/tests/test_examples.py @@ -15,4 +15,4 @@ def test_examples_are_valid_templates(name, text): result = convert_template(text, stack_name="demo") assert result["source"] == name assert result["summary"]["unsupported"] == 0 - assert not [n for n in result["notes"] if "was not converted" in n] + assert not [n for n in result["notes"] if "left out" in n] From 9e5a1783198153fe323c5ecd4aed1272b8744d9d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:24:21 +0000 Subject: [PATCH 5/5] Format the copy changes so ruff format passes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SmQPLQt2JAPt6J9EAPNF5F --- services/converter-api/tests/test_cfn_storage.py | 9 ++------- services/web/messages.py | 4 +++- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/services/converter-api/tests/test_cfn_storage.py b/services/converter-api/tests/test_cfn_storage.py index b445d00..1759328 100644 --- a/services/converter-api/tests/test_cfn_storage.py +++ b/services/converter-api/tests/test_cfn_storage.py @@ -369,10 +369,7 @@ def test_conditional_stream_and_stream_policy_is_reported(): assert 'stream_view_type = local.on ? "KEYS_ONLY" : null' in main assert "stream_view_type = null" not in main assert '# ResourcePolicy was left out. CloudFormation value: {"P": 1}' in main - assert any( - "'Policy.StreamSpecification.ResourcePolicy' yet" in n - for n in notes - ) + assert any("'Policy.StreamSpecification.ResourcePolicy' yet" in n for n in notes) assert "# StreamSpecification was left out" in main @@ -582,9 +579,7 @@ def test_conditional_and_computed_ecr_lifecycle_policy(): lifecycle = main.split('resource "aws_ecr_lifecycle_policy" "cond_lifecycle"')[1] assert lifecycle.startswith(" {\n count = local.on ? 1 : 0") assert main.count('# RegistryId was left out. CloudFormation value: "1"') == 2 - assert any( - "'Registry.LifecyclePolicy.RegistryId' yet" in n for n in notes - ) + assert any("'Registry.LifecyclePolicy.RegistryId' yet" in n for n in notes) assert "# LifecyclePolicy was left out" in main diff --git a/services/web/messages.py b/services/web/messages.py index e4e0384..a271bae 100644 --- a/services/web/messages.py +++ b/services/web/messages.py @@ -34,7 +34,9 @@ LENGTH_REQUIRED = "Content-Length required" TOO_LARGE = "The request is too large" -UNKNOWN_LOG_LEVEL = 'LOG_LEVEL "{value}" is unknown, so the service logs at info. Use one of: {allowed}.' +UNKNOWN_LOG_LEVEL = ( + 'LOG_LEVEL "{value}" is unknown, so the service logs at info. Use one of: {allowed}.' +) NOTES_TITLE = "# Conversion notes" NOTES_INTRO = (