From 9e320e8890118ae8a7e390ee357c2bad79b2ef5e Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Wed, 28 Oct 2026 09:06:52 +0100 Subject: [PATCH] Create Portainer environments on setup (#189011) --- .../components/portainer/config_flow.py | 27 ++++++++++++++----- .../components/portainer/strings.json | 3 ++- .../components/portainer/test_config_flow.py | 10 ++++++- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/portainer/config_flow.py b/homeassistant/components/portainer/config_flow.py index 90e3fe9d6e22..a42f196472e5 100644 --- a/homeassistant/components/portainer/config_flow.py +++ b/homeassistant/components/portainer/config_flow.py @@ -11,13 +11,14 @@ from pyportainer import ( PortainerConnectionError, PortainerTimeoutError, ) -from pyportainer.models.portainer import PortainerSystemStatus +from pyportainer.models.portainer import Endpoint, PortainerSystemStatus from homeassistant.config_entries import ( ConfigEntry, ConfigEntryState, ConfigFlow, ConfigFlowResult, + ConfigSubentryData, ConfigSubentryFlow, SubentryFlowResult, ) @@ -53,7 +54,7 @@ STEP_USER_DATA_SCHEMA = probatio.Schema( async def _validate_input( hass: HomeAssistant, data: dict[str, Any] -) -> PortainerSystemStatus: +) -> tuple[PortainerSystemStatus, list[Endpoint]]: """Validate the user input allows us to connect.""" client = Portainer( @@ -63,6 +64,7 @@ async def _validate_input( ) try: system_status = await client.portainer_system_status() + endpoints = await client.get_endpoints() except PortainerAuthenticationError: raise InvalidAuth from None except PortainerConnectionError as err: @@ -71,7 +73,7 @@ async def _validate_input( raise PortainerTimeout from err _LOGGER.debug("Connected to Portainer API: %s", data[CONF_URL]) - return system_status + return system_status, endpoints class PortainerConfigFlow(ConfigFlow, domain=DOMAIN): @@ -97,7 +99,7 @@ class PortainerConfigFlow(ConfigFlow, domain=DOMAIN): errors: dict[str, str] = {} if user_input is not None: try: - system_status = await _validate_input(self.hass, user_input) + system_status, endpoints = await _validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: @@ -111,7 +113,17 @@ class PortainerConfigFlow(ConfigFlow, domain=DOMAIN): await self.async_set_unique_id(system_status.instance_id) self._abort_if_unique_id_configured() return self.async_create_entry( - title=user_input[CONF_URL], data=user_input + title=user_input[CONF_URL], + data=user_input, + subentries=[ + ConfigSubentryData( + data={}, + subentry_type=SUBENTRY_TYPE_ENVIRONMENT, + title=endpoint.name or f"Endpoint {endpoint.id}", + unique_id=str(endpoint.id), + ) + for endpoint in endpoints + ], ) return self.async_show_form( @@ -180,7 +192,7 @@ class PortainerConfigFlow(ConfigFlow, domain=DOMAIN): if user_input: try: - system_status = await _validate_input( + system_status, _ = await _validate_input( self.hass, data={ **reconf_entry.data, @@ -237,6 +249,9 @@ class EnvironmentSubentryFlowHandler(ConfigSubentryFlow): return self.async_abort(reason="timeout_connect") except PortainerAuthenticationError: return self.async_abort(reason="invalid_auth") + except Exception: + _LOGGER.exception("Unexpected exception") + return self.async_abort(reason="unknown") configured_endpoint_ids = { subentry.unique_id for subentry in entry.subentries.values() diff --git a/homeassistant/components/portainer/strings.json b/homeassistant/components/portainer/strings.json index c5817e65a08f..9601e1ea63fb 100644 --- a/homeassistant/components/portainer/strings.json +++ b/homeassistant/components/portainer/strings.json @@ -56,7 +56,8 @@ "config_entry_not_loaded": "Cannot add an environment while the Portainer integration is not loaded.", "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", "no_new_environments": "All available environments on this Portainer server have already been added.", - "timeout_connect": "[%key:common::config_flow::error::timeout_connect%]" + "timeout_connect": "[%key:common::config_flow::error::timeout_connect%]", + "unknown": "[%key:common::config_flow::error::unknown%]" }, "entry_type": "Environment", "initiate_flow": { diff --git a/tests/components/portainer/test_config_flow.py b/tests/components/portainer/test_config_flow.py index 1232d3fb2e89..7cf89ea886af 100644 --- a/tests/components/portainer/test_config_flow.py +++ b/tests/components/portainer/test_config_flow.py @@ -57,6 +57,13 @@ async def test_form( assert result["title"] == "https://127.0.0.1:9000/" assert result["data"] == MOCK_TEST_CONFIG assert result["result"].unique_id == TEST_INSTANCE_ID + assert [ + (subentry.subentry_type, subentry.title, subentry.unique_id) + for subentry in result["result"].subentries.values() + ] == [ + (SUBENTRY_TYPE_ENVIRONMENT, "my-environment", "1"), + (SUBENTRY_TYPE_ENVIRONMENT, "my-edge-offline", "42"), + ] @pytest.mark.parametrize( @@ -394,6 +401,7 @@ async def test_environment_subentry_flow( (PortainerConnectionError("cannot connect"), "cannot_connect"), (PortainerTimeoutError("timeout"), "timeout_connect"), (PortainerAuthenticationError("invalid auth"), "invalid_auth"), + (Exception("Some other error"), "unknown"), ], ) async def test_environment_subentry_flow_exceptions( @@ -402,7 +410,7 @@ async def test_environment_subentry_flow_exceptions( exception: Exception, reason: str, ) -> None: - """Test the environment subentry flow aborts on connection errors.""" + """Test the environment subentry flow aborts on errors.""" entry = MockConfigEntry( domain=DOMAIN, title="Portainer test",