summaryrefslogtreecommitdiff
path: root/python-aws-cdk-aws-lambda-python-alpha.spec
blob: ec91ddf04b108c3b463f989daf6671934ef20729 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
%global _empty_manifest_terminate_build 0
Name:		python-aws-cdk.aws-lambda-python-alpha
Version:	2.83.0a0
Release:	1
Summary:	The CDK Construct Library for AWS Lambda in Python
License:	Apache-2.0
URL:		https://github.com/aws/aws-cdk
Source0:	https://mirrors.aliyun.com/pypi/web/packages/8f/88/2c3c0809d7ab4f59e0c423b8464e8677e86f766644d5f2646c37154f2636/aws-cdk.aws-lambda-python-alpha-2.83.0a0.tar.gz
BuildArch:	noarch

Requires:	python3-aws-cdk-lib
Requires:	python3-constructs
Requires:	python3-jsii
Requires:	python3-publication
Requires:	python3-typeguard

%description
<!--END STABILITY BANNER-->
This library provides constructs for Python Lambda functions.
To use this module, you will need to have Docker installed.
## Python Function
Define a `PythonFunction`:
```python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",  # required
    runtime=Runtime.PYTHON_3_8,  # required
    index="my_index.py",  # optional, defaults to 'index.py'
    handler="my_exported_func"
)
```
All other properties of `lambda.Function` are supported, see also the [AWS Lambda construct library](https://github.com/aws/aws-cdk/tree/main/packages/%40aws-cdk/aws-lambda).
## Python Layer
You may create a python-based lambda layer with `PythonLayerVersion`. If `PythonLayerVersion` detects a `requirements.txt`
or `Pipfile` or `poetry.lock` with the associated `pyproject.toml` at the entry path, then `PythonLayerVersion` will include the dependencies inline with your code in the
layer.
Define a `PythonLayerVersion`:
```python
python.PythonLayerVersion(self, "MyLayer",
    entry="/path/to/my/layer"
)
```
A layer can also be used as a part of a `PythonFunction`:
```python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",
    runtime=Runtime.PYTHON_3_8,
    layers=[
        python.PythonLayerVersion(self, "MyLayer",
            entry="/path/to/my/layer"
        )
    ]
)
```
## Packaging
If `requirements.txt`, `Pipfile` or `poetry.lock` exists at the entry path, the construct will handle installing all required modules in a [Lambda compatible Docker container](https://gallery.ecr.aws/sam/build-python3.7) according to the `runtime` and with the Docker platform based on the target architecture of the Lambda function.
Python bundles are only recreated and published when a file in a source directory has changed.
Therefore (and as a general best-practice), it is highly recommended to commit a lockfile with a
list of all transitive dependencies and their exact versions. This will ensure that when any dependency version is updated, the bundle asset is recreated and uploaded.
To that end, we recommend using [`pipenv`] or [`poetry`] which have lockfile support.
* [`pipenv`](https://pipenv-fork.readthedocs.io/en/latest/basics.html#example-pipfile-lock)
* [`poetry`](https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control)
Packaging is executed using the `Packaging` class, which:
1. Infers the packaging type based on the files present.
2. If it sees a `Pipfile` or a `poetry.lock` file, it exports it to a compatible `requirements.txt` file with credentials (if they're available in the source files or in the bundling container).
3. Installs dependencies using `pip`.
4. Copies the dependencies into an asset that is bundled for the Lambda package.
**Lambda with a requirements.txt**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry path
```
**Lambda with a Pipfile**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock file
```
**Lambda with a poetry.lock**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── poetry.lock # your poetry lock file has to be present at the entry path
```
**Excluding source files**
You can exclude files from being copied using the optional bundling string array parameter `assetExcludes`
```python
python.PythonFunction(self, "function",
    entry="/path/to/poetry-function",
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        # translates to `rsync --exclude='.venv'`
        asset_excludes=[".venv"]
    )
)
```
## Custom Bundling
Custom bundling can be performed by passing in additional build arguments that point to index URLs to private repos, or by using an entirely custom Docker images for bundling dependencies. The build args currently supported are:
* `PIP_INDEX_URL`
* `PIP_EXTRA_INDEX_URL`
* `HTTPS_PROXY`
Additional build args for bundling that refer to PyPI indexes can be specified as:
```python
entry = "/path/to/function"
image = DockerImage.from_build(entry)
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": "https://your.index.url/simple/", "PIP_EXTRA_INDEX_URL": "https://your.extra-index.url/simple/"}
    )
)
```
If using a custom Docker image for bundling, the dependencies are installed with `pip`, `pipenv` or `poetry` by using the `Packaging` class. A different bundling Docker image that is in the same directory as the function can be specified as:
```python
entry = "/path/to/function"
image = DockerImage.from_build(entry)
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(image=image)
)
```
You can set additional Docker options to configure the build environment:
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        network="host",
        security_opt="no-new-privileges",
        user="user:group",
        volumes_from=["777f7dc92da7"],
        volumes=[DockerVolume(host_path="/host-path", container_path="/container-path")]
    )
)
```
## Custom Bundling with Code Artifact
To use a Code Artifact PyPI repo, the `PIP_INDEX_URL` for bundling the function can be customized (requires AWS CLI in the build environment):
```python
from child_process import exec_sync
entry = "/path/to/function"
image = DockerImage.from_build(entry)
domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()
index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        environment={"PIP_INDEX_URL": index_url}
    )
)
```
The index URL or the token are only used during bundling and thus not included in the final asset. Setting only environment variable for `PIP_INDEX_URL` or `PIP_EXTRA_INDEX_URL` should work for accesing private Python repositories with `pip`, `pipenv` and `poetry` based dependencies.
If you also want to use the Code Artifact repo for building the base Docker image for bundling, use `buildArgs`. However, note that setting custom build args for bundling will force the base bundling image to be rebuilt every time (i.e. skip the Docker cache). Build args can be customized as:
```python
from child_process import exec_sync
entry = "/path/to/function"
image = DockerImage.from_build(entry)
domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()
index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": index_url}
    )
)
```
## Command hooks
It is  possible to run additional commands by specifying the `commandHooks` prop:
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        command_hooks={
            # run tests
            def before_bundling(self, input_dir):
                return ["pytest"],
            def after_bundling(self, input_dir):
                return ["pylint"]
        }
    )
)
```
The following hooks are available:
* `beforeBundling`: runs before all bundling commands
* `afterBundling`: runs after all bundling commands
They all receive the directory containing the dependencies file (`inputDir`) and the
directory where the bundled asset will be output (`outputDir`). They must return
an array of commands to run. Commands are chained with `&&`.
The commands will run in the environment in which bundling occurs: inside the
container for Docker bundling or on the host OS for local bundling.
## Docker based bundling in complex Docker configurations
By default the input and output of Docker based bundling is handled via bind mounts.
In situtations where this does not work, like Docker-in-Docker setups or when using a remote Docker socket, you can configure an alternative, but slower, variant that also works in these situations.
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        bundling_file_access=BundlingFileAccess.VOLUME_COPY
    )
)
```
## Troubleshooting
### Containerfile: no such file or directory
If you are on a Mac, using [Finch](https://github.com/runfinch/finch) instead of Docker, and see an error
like this:
```txt
lstat /private/var/folders/zx/d5wln9n10sn0tcj1v9798f1c0000gr/T/jsii-kernel-9VYgrO/node_modules/@aws-cdk/aws-lambda-python-alpha/lib/Containerfile: no such file or directory
```
That is a sign that your temporary directory has not been mapped into the Finch VM. Add the following to `~/.finch/finch.yaml`:
```yaml
additional_directories:
  - path: /private/var/folders/
  - path: /var/folders/
```
Then restart the Finch VM by running `finch vm stop && finch vm start`.

%package -n python3-aws-cdk.aws-lambda-python-alpha
Summary:	The CDK Construct Library for AWS Lambda in Python
Provides:	python-aws-cdk.aws-lambda-python-alpha
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-aws-cdk.aws-lambda-python-alpha
<!--END STABILITY BANNER-->
This library provides constructs for Python Lambda functions.
To use this module, you will need to have Docker installed.
## Python Function
Define a `PythonFunction`:
```python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",  # required
    runtime=Runtime.PYTHON_3_8,  # required
    index="my_index.py",  # optional, defaults to 'index.py'
    handler="my_exported_func"
)
```
All other properties of `lambda.Function` are supported, see also the [AWS Lambda construct library](https://github.com/aws/aws-cdk/tree/main/packages/%40aws-cdk/aws-lambda).
## Python Layer
You may create a python-based lambda layer with `PythonLayerVersion`. If `PythonLayerVersion` detects a `requirements.txt`
or `Pipfile` or `poetry.lock` with the associated `pyproject.toml` at the entry path, then `PythonLayerVersion` will include the dependencies inline with your code in the
layer.
Define a `PythonLayerVersion`:
```python
python.PythonLayerVersion(self, "MyLayer",
    entry="/path/to/my/layer"
)
```
A layer can also be used as a part of a `PythonFunction`:
```python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",
    runtime=Runtime.PYTHON_3_8,
    layers=[
        python.PythonLayerVersion(self, "MyLayer",
            entry="/path/to/my/layer"
        )
    ]
)
```
## Packaging
If `requirements.txt`, `Pipfile` or `poetry.lock` exists at the entry path, the construct will handle installing all required modules in a [Lambda compatible Docker container](https://gallery.ecr.aws/sam/build-python3.7) according to the `runtime` and with the Docker platform based on the target architecture of the Lambda function.
Python bundles are only recreated and published when a file in a source directory has changed.
Therefore (and as a general best-practice), it is highly recommended to commit a lockfile with a
list of all transitive dependencies and their exact versions. This will ensure that when any dependency version is updated, the bundle asset is recreated and uploaded.
To that end, we recommend using [`pipenv`] or [`poetry`] which have lockfile support.
* [`pipenv`](https://pipenv-fork.readthedocs.io/en/latest/basics.html#example-pipfile-lock)
* [`poetry`](https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control)
Packaging is executed using the `Packaging` class, which:
1. Infers the packaging type based on the files present.
2. If it sees a `Pipfile` or a `poetry.lock` file, it exports it to a compatible `requirements.txt` file with credentials (if they're available in the source files or in the bundling container).
3. Installs dependencies using `pip`.
4. Copies the dependencies into an asset that is bundled for the Lambda package.
**Lambda with a requirements.txt**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry path
```
**Lambda with a Pipfile**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock file
```
**Lambda with a poetry.lock**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── poetry.lock # your poetry lock file has to be present at the entry path
```
**Excluding source files**
You can exclude files from being copied using the optional bundling string array parameter `assetExcludes`
```python
python.PythonFunction(self, "function",
    entry="/path/to/poetry-function",
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        # translates to `rsync --exclude='.venv'`
        asset_excludes=[".venv"]
    )
)
```
## Custom Bundling
Custom bundling can be performed by passing in additional build arguments that point to index URLs to private repos, or by using an entirely custom Docker images for bundling dependencies. The build args currently supported are:
* `PIP_INDEX_URL`
* `PIP_EXTRA_INDEX_URL`
* `HTTPS_PROXY`
Additional build args for bundling that refer to PyPI indexes can be specified as:
```python
entry = "/path/to/function"
image = DockerImage.from_build(entry)
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": "https://your.index.url/simple/", "PIP_EXTRA_INDEX_URL": "https://your.extra-index.url/simple/"}
    )
)
```
If using a custom Docker image for bundling, the dependencies are installed with `pip`, `pipenv` or `poetry` by using the `Packaging` class. A different bundling Docker image that is in the same directory as the function can be specified as:
```python
entry = "/path/to/function"
image = DockerImage.from_build(entry)
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(image=image)
)
```
You can set additional Docker options to configure the build environment:
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        network="host",
        security_opt="no-new-privileges",
        user="user:group",
        volumes_from=["777f7dc92da7"],
        volumes=[DockerVolume(host_path="/host-path", container_path="/container-path")]
    )
)
```
## Custom Bundling with Code Artifact
To use a Code Artifact PyPI repo, the `PIP_INDEX_URL` for bundling the function can be customized (requires AWS CLI in the build environment):
```python
from child_process import exec_sync
entry = "/path/to/function"
image = DockerImage.from_build(entry)
domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()
index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        environment={"PIP_INDEX_URL": index_url}
    )
)
```
The index URL or the token are only used during bundling and thus not included in the final asset. Setting only environment variable for `PIP_INDEX_URL` or `PIP_EXTRA_INDEX_URL` should work for accesing private Python repositories with `pip`, `pipenv` and `poetry` based dependencies.
If you also want to use the Code Artifact repo for building the base Docker image for bundling, use `buildArgs`. However, note that setting custom build args for bundling will force the base bundling image to be rebuilt every time (i.e. skip the Docker cache). Build args can be customized as:
```python
from child_process import exec_sync
entry = "/path/to/function"
image = DockerImage.from_build(entry)
domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()
index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": index_url}
    )
)
```
## Command hooks
It is  possible to run additional commands by specifying the `commandHooks` prop:
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        command_hooks={
            # run tests
            def before_bundling(self, input_dir):
                return ["pytest"],
            def after_bundling(self, input_dir):
                return ["pylint"]
        }
    )
)
```
The following hooks are available:
* `beforeBundling`: runs before all bundling commands
* `afterBundling`: runs after all bundling commands
They all receive the directory containing the dependencies file (`inputDir`) and the
directory where the bundled asset will be output (`outputDir`). They must return
an array of commands to run. Commands are chained with `&&`.
The commands will run in the environment in which bundling occurs: inside the
container for Docker bundling or on the host OS for local bundling.
## Docker based bundling in complex Docker configurations
By default the input and output of Docker based bundling is handled via bind mounts.
In situtations where this does not work, like Docker-in-Docker setups or when using a remote Docker socket, you can configure an alternative, but slower, variant that also works in these situations.
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        bundling_file_access=BundlingFileAccess.VOLUME_COPY
    )
)
```
## Troubleshooting
### Containerfile: no such file or directory
If you are on a Mac, using [Finch](https://github.com/runfinch/finch) instead of Docker, and see an error
like this:
```txt
lstat /private/var/folders/zx/d5wln9n10sn0tcj1v9798f1c0000gr/T/jsii-kernel-9VYgrO/node_modules/@aws-cdk/aws-lambda-python-alpha/lib/Containerfile: no such file or directory
```
That is a sign that your temporary directory has not been mapped into the Finch VM. Add the following to `~/.finch/finch.yaml`:
```yaml
additional_directories:
  - path: /private/var/folders/
  - path: /var/folders/
```
Then restart the Finch VM by running `finch vm stop && finch vm start`.

%package help
Summary:	Development documents and examples for aws-cdk.aws-lambda-python-alpha
Provides:	python3-aws-cdk.aws-lambda-python-alpha-doc
%description help
<!--END STABILITY BANNER-->
This library provides constructs for Python Lambda functions.
To use this module, you will need to have Docker installed.
## Python Function
Define a `PythonFunction`:
```python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",  # required
    runtime=Runtime.PYTHON_3_8,  # required
    index="my_index.py",  # optional, defaults to 'index.py'
    handler="my_exported_func"
)
```
All other properties of `lambda.Function` are supported, see also the [AWS Lambda construct library](https://github.com/aws/aws-cdk/tree/main/packages/%40aws-cdk/aws-lambda).
## Python Layer
You may create a python-based lambda layer with `PythonLayerVersion`. If `PythonLayerVersion` detects a `requirements.txt`
or `Pipfile` or `poetry.lock` with the associated `pyproject.toml` at the entry path, then `PythonLayerVersion` will include the dependencies inline with your code in the
layer.
Define a `PythonLayerVersion`:
```python
python.PythonLayerVersion(self, "MyLayer",
    entry="/path/to/my/layer"
)
```
A layer can also be used as a part of a `PythonFunction`:
```python
python.PythonFunction(self, "MyFunction",
    entry="/path/to/my/function",
    runtime=Runtime.PYTHON_3_8,
    layers=[
        python.PythonLayerVersion(self, "MyLayer",
            entry="/path/to/my/layer"
        )
    ]
)
```
## Packaging
If `requirements.txt`, `Pipfile` or `poetry.lock` exists at the entry path, the construct will handle installing all required modules in a [Lambda compatible Docker container](https://gallery.ecr.aws/sam/build-python3.7) according to the `runtime` and with the Docker platform based on the target architecture of the Lambda function.
Python bundles are only recreated and published when a file in a source directory has changed.
Therefore (and as a general best-practice), it is highly recommended to commit a lockfile with a
list of all transitive dependencies and their exact versions. This will ensure that when any dependency version is updated, the bundle asset is recreated and uploaded.
To that end, we recommend using [`pipenv`] or [`poetry`] which have lockfile support.
* [`pipenv`](https://pipenv-fork.readthedocs.io/en/latest/basics.html#example-pipfile-lock)
* [`poetry`](https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control)
Packaging is executed using the `Packaging` class, which:
1. Infers the packaging type based on the files present.
2. If it sees a `Pipfile` or a `poetry.lock` file, it exports it to a compatible `requirements.txt` file with credentials (if they're available in the source files or in the bundling container).
3. Installs dependencies using `pip`.
4. Copies the dependencies into an asset that is bundled for the Lambda package.
**Lambda with a requirements.txt**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry path
```
**Lambda with a Pipfile**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock file
```
**Lambda with a poetry.lock**
```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── poetry.lock # your poetry lock file has to be present at the entry path
```
**Excluding source files**
You can exclude files from being copied using the optional bundling string array parameter `assetExcludes`
```python
python.PythonFunction(self, "function",
    entry="/path/to/poetry-function",
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        # translates to `rsync --exclude='.venv'`
        asset_excludes=[".venv"]
    )
)
```
## Custom Bundling
Custom bundling can be performed by passing in additional build arguments that point to index URLs to private repos, or by using an entirely custom Docker images for bundling dependencies. The build args currently supported are:
* `PIP_INDEX_URL`
* `PIP_EXTRA_INDEX_URL`
* `HTTPS_PROXY`
Additional build args for bundling that refer to PyPI indexes can be specified as:
```python
entry = "/path/to/function"
image = DockerImage.from_build(entry)
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": "https://your.index.url/simple/", "PIP_EXTRA_INDEX_URL": "https://your.extra-index.url/simple/"}
    )
)
```
If using a custom Docker image for bundling, the dependencies are installed with `pip`, `pipenv` or `poetry` by using the `Packaging` class. A different bundling Docker image that is in the same directory as the function can be specified as:
```python
entry = "/path/to/function"
image = DockerImage.from_build(entry)
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(image=image)
)
```
You can set additional Docker options to configure the build environment:
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        network="host",
        security_opt="no-new-privileges",
        user="user:group",
        volumes_from=["777f7dc92da7"],
        volumes=[DockerVolume(host_path="/host-path", container_path="/container-path")]
    )
)
```
## Custom Bundling with Code Artifact
To use a Code Artifact PyPI repo, the `PIP_INDEX_URL` for bundling the function can be customized (requires AWS CLI in the build environment):
```python
from child_process import exec_sync
entry = "/path/to/function"
image = DockerImage.from_build(entry)
domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()
index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        environment={"PIP_INDEX_URL": index_url}
    )
)
```
The index URL or the token are only used during bundling and thus not included in the final asset. Setting only environment variable for `PIP_INDEX_URL` or `PIP_EXTRA_INDEX_URL` should work for accesing private Python repositories with `pip`, `pipenv` and `poetry` based dependencies.
If you also want to use the Code Artifact repo for building the base Docker image for bundling, use `buildArgs`. However, note that setting custom build args for bundling will force the base bundling image to be rebuilt every time (i.e. skip the Docker cache). Build args can be customized as:
```python
from child_process import exec_sync
entry = "/path/to/function"
image = DockerImage.from_build(entry)
domain = "my-domain"
domain_owner = "111122223333"
repo_name = "my_repo"
region = "us-east-1"
code_artifact_auth_token = exec_sync(f"aws codeartifact get-authorization-token --domain {domain} --domain-owner {domainOwner} --query authorizationToken --output text").to_string().trim()
index_url = f"https://aws:{codeArtifactAuthToken}@{domain}-{domainOwner}.d.codeartifact.{region}.amazonaws.com/pypi/{repoName}/simple/"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        build_args={"PIP_INDEX_URL": index_url}
    )
)
```
## Command hooks
It is  possible to run additional commands by specifying the `commandHooks` prop:
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        command_hooks={
            # run tests
            def before_bundling(self, input_dir):
                return ["pytest"],
            def after_bundling(self, input_dir):
                return ["pylint"]
        }
    )
)
```
The following hooks are available:
* `beforeBundling`: runs before all bundling commands
* `afterBundling`: runs after all bundling commands
They all receive the directory containing the dependencies file (`inputDir`) and the
directory where the bundled asset will be output (`outputDir`). They must return
an array of commands to run. Commands are chained with `&&`.
The commands will run in the environment in which bundling occurs: inside the
container for Docker bundling or on the host OS for local bundling.
## Docker based bundling in complex Docker configurations
By default the input and output of Docker based bundling is handled via bind mounts.
In situtations where this does not work, like Docker-in-Docker setups or when using a remote Docker socket, you can configure an alternative, but slower, variant that also works in these situations.
```python
entry = "/path/to/function"
python.PythonFunction(self, "function",
    entry=entry,
    runtime=Runtime.PYTHON_3_8,
    bundling=python.BundlingOptions(
        bundling_file_access=BundlingFileAccess.VOLUME_COPY
    )
)
```
## Troubleshooting
### Containerfile: no such file or directory
If you are on a Mac, using [Finch](https://github.com/runfinch/finch) instead of Docker, and see an error
like this:
```txt
lstat /private/var/folders/zx/d5wln9n10sn0tcj1v9798f1c0000gr/T/jsii-kernel-9VYgrO/node_modules/@aws-cdk/aws-lambda-python-alpha/lib/Containerfile: no such file or directory
```
That is a sign that your temporary directory has not been mapped into the Finch VM. Add the following to `~/.finch/finch.yaml`:
```yaml
additional_directories:
  - path: /private/var/folders/
  - path: /var/folders/
```
Then restart the Finch VM by running `finch vm stop && finch vm start`.

%prep
%autosetup -n aws-cdk.aws-lambda-python-alpha-2.83.0a0

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-aws-cdk.aws-lambda-python-alpha -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri Jun 09 2023 Python_Bot <Python_Bot@openeuler.org> - 2.83.0a0-1
- Package Spec generated