Skip to content

Commit acec0de

Browse files
committed
feat: add a --subscription parameter to handle multitenanted code and fix bugs
Add a token publish mode instead of mapping Azure credentials. Use without-hashes because Poetry's export is incompatible with Oryx.
1 parent c9a6605 commit acec0de

6 files changed

Lines changed: 77 additions & 24 deletions

File tree

‎src/apt_package_function/azcmd.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import json
66
import logging
77
import subprocess
8-
from typing import Any, Dict, List
8+
from typing import Any, Dict, List, Optional
99

1010
log = logging.getLogger(__name__)
1111
log.addHandler(logging.NullHandler())
@@ -16,9 +16,11 @@ class AzCmd:
1616

1717
OUTPUT: str
1818

19-
def __init__(self, cmd: List[str]) -> None:
19+
def __init__(self, cmd: List[str], subscription: Optional[str] = None) -> None:
2020
"""Create an AzCmd object"""
2121
self.cmd = cmd
22+
if subscription:
23+
self.cmd = [*cmd, "--subscription", subscription]
2224

2325
def _run_cmd(self, cmd: List[str]) -> Any: # noqa: ANN401
2426
"""Runs a command and may return output"""

‎src/apt_package_function/bicep_deployment.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import logging
66
from pathlib import Path
7-
from typing import Any, Dict
7+
from typing import Any, Dict, Optional
88

99
from apt_package_function.azcmd import AzCmdJson, AzCmdNone
1010

@@ -22,12 +22,14 @@ def __init__(
2222
template_file: Path,
2323
parameters: Dict[str, Any],
2424
description: str,
25+
subscription: Optional[str] = None,
2526
) -> None:
2627
"""Create a BicepDeployment object."""
2728
self.deployment_name = deployment_name
2829
self.resource_group_name = resource_group_name
2930
self.template_file = template_file
3031
self.description = description
32+
self.subscription = subscription
3133

3234
# Convert the set of parameters to a list of flags
3335
self.parameters = []
@@ -49,7 +51,8 @@ def create(self) -> None:
4951
"--template-file",
5052
str(self.template_file),
5153
*self.parameters,
52-
]
54+
],
55+
subscription=self.subscription,
5356
)
5457
log.info(
5558
"Deploying: %s (in resource group: %s)",
@@ -73,7 +76,8 @@ def outputs(self) -> Dict[str, Any]:
7376
self.resource_group_name,
7477
"--query",
7578
"properties.outputs",
76-
]
79+
],
80+
subscription=self.subscription,
7781
)
7882
data = cmd.run_expect_dict()
7983

‎src/apt_package_function/create_resources.py‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,17 @@ def main() -> None:
4242
"--suffix",
4343
help="Unique suffix for the repository name. If not provided, a random suffix will be generated. Must be 14 characters or fewer.",
4444
)
45+
parser.add_argument(
46+
"--subscription",
47+
help="The subscription to create resources in. If not provided, the active 'az' subscription is used.",
48+
)
4549
args = parser.parse_args()
4650

4751
if args.suffix and len(args.suffix) > 14:
4852
raise ValueError("Suffix must be 14 characters or fewer.")
4953

5054
# Create the resource group
51-
create_rg(args.resource_group, args.location)
55+
create_rg(args.resource_group, args.location, subscription=args.subscription)
5256

5357
# Ensure requirements.txt exists
5458
extract_requirements(Path("requirements.txt"))
@@ -74,6 +78,7 @@ def main() -> None:
7478
template_file=Path("rg.bicep"),
7579
parameters=initial_parameters,
7680
description="initial resources",
81+
subscription=args.subscription,
7782
)
7883
initial_resources.create()
7984

@@ -87,10 +92,16 @@ def main() -> None:
8792
# Create the function app
8893
funcapp: FuncApp
8994
if not args.no_shared_keys:
90-
funcapp = FuncAppZip(name=function_app_name, resource_group=args.resource_group)
95+
funcapp = FuncAppZip(
96+
name=function_app_name,
97+
resource_group=args.resource_group,
98+
subscription=args.subscription,
99+
)
91100
else:
92101
funcapp = FuncAppBundle(
93-
name=function_app_name, resource_group=args.resource_group
102+
name=function_app_name,
103+
resource_group=args.resource_group,
104+
subscription=args.subscription,
94105
)
95106

96107
with funcapp as cm:
@@ -105,6 +116,7 @@ def main() -> None:
105116
template_file=Path("rg_add_eventgrid.bicep"),
106117
parameters=common_parameters,
107118
description="Event Grid trigger configuration",
119+
subscription=args.subscription,
108120
)
109121
event_grid_deployment.create()
110122

‎src/apt_package_function/func_app.py‎

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import json
66
import logging
7+
import os
78
import subprocess
89
import tempfile
910
import time
@@ -22,11 +23,18 @@
2223
class FuncApp:
2324
"""Basic class for managing function apps."""
2425

25-
def __init__(self, name: str, resource_group: str, output_path: Path) -> None:
26+
def __init__(
27+
self,
28+
name: str,
29+
resource_group: str,
30+
output_path: Path,
31+
subscription: Optional[str] = None,
32+
) -> None:
2633
"""Create a FuncApp object."""
2734
self.name = name
2835
self.resource_group = resource_group
2936
self.output_path = output_path
37+
self.subscription = subscription
3038

3139
def wait_for_event_trigger(self) -> None:
3240
"""Wait until the function app has an eventGridTrigger function."""
@@ -42,7 +50,8 @@ def wait_for_event_trigger(self) -> None:
4250
self.resource_group,
4351
"--query",
4452
"[].name",
45-
]
53+
],
54+
subscription=self.subscription,
4655
)
4756
log.info("Awaiting event trigger on function app %s", self.name)
4857

@@ -85,10 +94,14 @@ def deploy(self) -> None:
8594
class FuncAppZip(FuncApp):
8695
"""Class for managing zipped function apps."""
8796

88-
def __init__(self, name: str, resource_group: str) -> None:
97+
def __init__(
98+
self, name: str, resource_group: str, subscription: Optional[str] = None
99+
) -> None:
89100
"""Create a FuncAppZip object."""
90101
self.tempfile = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
91-
super().__init__(name, resource_group, Path(self.tempfile.name))
102+
super().__init__(
103+
name, resource_group, Path(self.tempfile.name), subscription=subscription
104+
)
92105

93106
self.zip_paths = [
94107
Path("host.json"),
@@ -119,7 +132,8 @@ def deploy(self) -> None:
119132
str(self.output_path),
120133
"--build-remote",
121134
"true",
122-
]
135+
],
136+
subscription=self.subscription,
123137
)
124138
log.info("Deploying function app code to %s", self.name)
125139
cmd.run()
@@ -129,34 +143,48 @@ def deploy(self) -> None:
129143
class FuncAppBundle(FuncApp):
130144
"""Publishes the function app using the core-tools tooling."""
131145

132-
def __init__(self, name: str, resource_group: str) -> None:
146+
def __init__(
147+
self, name: str, resource_group: str, subscription: Optional[str] = None
148+
) -> None:
133149
"""Create a FuncAppBundle object."""
134-
super().__init__(name, resource_group, Path("function_app.zip"))
150+
super().__init__(
151+
name, resource_group, Path("function_app.zip"), subscription=subscription
152+
)
135153

136154
def deploy(self) -> None:
137155
"""Deploy the function application."""
138156
log.info("Deploying function app code")
139157
cwd = Path.cwd()
140-
home = Path.home()
141-
azure_config = home / ".azure"
158+
159+
# Mint an access token on the host: the host 'az' can read its own
160+
# credential cache, whereas the (older) 'az' inside the core-tools image
161+
# cannot deserialise a cache written by a newer host 'az'. So instead of
162+
# mounting ~/.azure into the container, pass a token to 'func' directly.
163+
token_cmd = ["az", "account", "get-access-token", "--query", "accessToken"]
164+
token = AzCmdJson(token_cmd, subscription=self.subscription).run()
165+
166+
# Pass the token via the environment so it never appears in the logged
167+
# command line or the container's process arguments.
168+
func_cmd = f"func azure functionapp publish {self.name} --python --build remote --access-token \"$FUNC_ACCESS_TOKEN\""
169+
if self.subscription:
170+
func_cmd += f" --subscription {self.subscription}"
142171

143172
# Publish the application using the core-tools tooling
144173
cmd = [
145174
"docker",
146175
"run",
147-
"-it",
148176
"--rm",
149-
"-v",
150-
f"{azure_config}:/root/.azure",
177+
"-e",
178+
"FUNC_ACCESS_TOKEN",
151179
"-v",
152180
f"{cwd}:/function_app",
153181
"-w",
154182
"/function_app",
155183
"mcr.microsoft.com/azure-functions/python:4-python3.11-core-tools",
156184
"bash",
157185
"-c",
158-
f"func azure functionapp publish {self.name} --python --build remote",
186+
func_cmd,
159187
]
160188
log.debug("Running %s", cmd)
161-
subprocess.run(cmd, check=True)
189+
subprocess.run(cmd, check=True, env={**os.environ, "FUNC_ACCESS_TOKEN": token})
162190
log.info("Function app code published to %s", self.name)

‎src/apt_package_function/poetry.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ def extract_requirements(requirements_path: Path) -> None:
1919
"requirements.txt",
2020
"--output",
2121
str(requirements_path),
22+
# Hashes flip pip into --require-hashes mode, which the Flex Consumption
23+
# remote (Oryx) build rejects for poetry's multi-marker entries.
24+
"--without-hashes",
2225
]
2326
log.debug("Running %s", cmd)
2427
subprocess.run(cmd, check=True)

‎src/apt_package_function/resource_group.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,23 @@
33
"""Manages resource groups."""
44

55
import logging
6+
from typing import Optional
67

78
from apt_package_function.azcmd import AzCmdNone
89

910
log = logging.getLogger(__name__)
1011
log.addHandler(logging.NullHandler())
1112

1213

13-
def create_rg(resource_group: str, location: str) -> None:
14+
def create_rg(
15+
resource_group: str, location: str, subscription: Optional[str] = None
16+
) -> None:
1417
"""Create a resource group."""
1518
log.debug("Creating resource group %s in location %s", resource_group, location)
1619

1720
cmd = AzCmdNone(
18-
["az", "group", "create", "--name", resource_group, "--location", location]
21+
["az", "group", "create", "--name", resource_group, "--location", location],
22+
subscription=subscription,
1923
)
2024
cmd.run()
2125
log.info("Created resource group %s in location %s", resource_group, location)

0 commit comments

Comments
 (0)