Skip to content

Commit 8645909

Browse files
authored
Merge branch 'next-release/main' into renbran/setup-data-gen-2-android-swift
2 parents ecad092 + b7e15e8 commit 8645909

File tree

9 files changed

+220
-55
lines changed

9 files changed

+220
-55
lines changed
Loading

src/directory/directory.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ export const directory = {
229229
path: 'src/pages/[platform]/build-a-backend/functions/index.mdx',
230230
children: [
231231
{
232-
path: 'src/pages/[platform]/build-a-backend/functions/set-up-function/index.mdx'
232+
path: 'src/pages/[platform]/build-a-backend/functions/define-function/index.mdx'
233233
},
234234
{
235235
path: 'src/pages/[platform]/build-a-backend/functions/environment-variables-and-secrets/index.mdx'

src/fragments/lib/predictions/js/getting-started.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ Amplify.configure({
9292
identityPoolId: 'us-east-1:xxx-xxx-xxx-xxx-xxx',
9393
region: 'us-east-1'
9494
},
95-
predictions: {
95+
Predictions: {
9696
convert: {
9797
translateText: {
9898
region: 'us-east-1',

src/pages/[platform]/build-a-backend/functions/set-up-function/index.mdx renamed to src/pages/[platform]/build-a-backend/functions/define-function/index.mdx

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { getCustomStaticPath } from '@/utils/getCustomStaticPath';
22

33
export const meta = {
4-
title: 'Set up an Amplify Function',
4+
title: 'Define an Amplify Function',
55
description:
66
'Use AWS Lambda functions to perform tasks and customize workflows.',
77
platforms: [
@@ -29,44 +29,49 @@ export function getStaticProps(context) {
2929
};
3030
}
3131

32-
Amplify Functions are powered by [AWS Lambda](https://aws.amazon.com/lambda/), and allow you to perform a wide variety of customization through contained _functions_.
32+
Amplify Functions are powered by [AWS Lambda](https://aws.amazon.com/lambda/), and allow you to perform a wide variety of customization through self-contained _functions_. Functions can respond to events from other resources, execute some logic in-between events like an authentication flow, or act as standalone jobs. They are used in a variety of settings and use cases:
33+
34+
- Authentication flow customizations (e.g. attribute validations, allowlisting email domains)
35+
- Resolvers for GraphQL APIs
36+
- Handlers for individual REST API routes, or to host an entire API
37+
- Scheduled jobs
3338

3439
## Define a Function
3540

36-
To get started, create a new directory and a resource file, `amplify/functions/my-demo-function/resource.ts`. Then, define the Function with `defineFunction`:
41+
To get started, create a new directory and a resource file, `amplify/functions/say-hello/resource.ts`. Then, define the Function with `defineFunction`:
3742

38-
```ts title="amplify/functions/my-demo-function/resource.ts"
43+
```ts title="amplify/functions/say-hello/resource.ts"
3944
import { defineFunction } from '@aws-amplify/backend';
4045

41-
export const myDemoFunction = defineFunction({
46+
export const sayHello = defineFunction({
4247
// optionally specify a name for the Function (defaults to directory name)
43-
name: 'my-demo-function',
48+
name: 'say-hello',
4449
// optionally specify a path to your handler (defaults to "./handler.ts")
4550
entry: './handler.ts'
4651
});
4752
```
4853

49-
Next, create the corresponding handler file at `amplify/functions/my-demo-function/handler.ts`. This is where your function code will go.
54+
Next, create the corresponding handler file at `amplify/functions/say-hello/handler.ts`. This is where your function code will go.
5055

51-
```ts title="amplify/functions/my-demo-function/handler.ts"
56+
```ts title="amplify/functions/say-hello/handler.ts"
5257
export const handler = async (event) => {
5358
// your function code goes here
54-
return 'You made a function!';
59+
return 'Hello, World!';
5560
};
5661
```
5762

58-
The handler file _must_ export an async function named "handler". This is the entry point to your function. For more information on writing functions, refer to the [AWS documentation for Lambda function handlers using Node.js](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html).
63+
The handler file _must_ export a function named "handler". This is the entry point to your function. For more information on writing functions, refer to the [AWS documentation for Lambda function handlers using Node.js](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html).
5964

6065
Lastly, this function needs to be added to your backend.
6166

6267
```ts title="amplify/backend.ts"
6368
import { defineBackend } from '@aws-amplify/backend';
6469
// highlight-next-line
65-
import { myDemoFunction } from './functions/my-demo-function/resource';
70+
import { sayHello } from './functions/say-hello/resource';
6671

6772
defineBackend({
6873
// highlight-next-line
69-
myDemoFunction
74+
sayHello
7075
});
7176
```
7277

@@ -76,7 +81,7 @@ Now when you run `npx amplify sandbox` or deploy your app on Amplify, it will in
7681

7782
Now that you have completed setting up your first Function, you may also want to add some additional features or modify a few settings. We recommend you learn more about:
7883

79-
- [Environment variables and secrets](../environment-variables-and-secrets/)
80-
- [Grant access to other resources](../grant-access-to-other-resources/)
81-
- [Explore example use cases](../examples/)
82-
- [Modifying underlying resources with CDK](../modify-resources-with-cdk/)
84+
- [Environment variables and secrets](/[platform]/build-a-backend/functions/environment-variables-and-secrets/)
85+
- [Grant access to other resources](/[platform]/build-a-backend/functions/grant-access-to-other-resources/)
86+
- [Explore example use cases](/[platform]/build-a-backend/functions/examples/)
87+
- [Modifying underlying resources with CDK](/[platform]/build-a-backend/functions/modify-resources-with-cdk/)

src/pages/[platform]/build-a-backend/functions/environment-variables-and-secrets/index.mdx

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export function getStaticProps() {
2929
};
3030
}
3131

32-
Amplify Gen 2 Functions support setting environment variables and secrets on the `environment` property of `defineFunction`.
32+
Amplify Functions support setting environment variables and secrets on the `environment` property of `defineFunction`.
3333

3434
<Callout warning>
3535

@@ -41,25 +41,26 @@ Amplify Gen 2 Functions support setting environment variables and secrets on the
4141

4242
Environment variables can be configured in `defineFunction` using the `environment` property.
4343

44-
```ts title="amplify/functions/my-demo-function/resource.ts"
44+
```ts title="amplify/functions/say-hello/resource.ts"
4545
import { defineFunction } from '@aws-amplify/backend';
4646

47-
export const myDemoFunction = defineFunction({
47+
export const sayHello = defineFunction({
4848
environment: {
49-
ENV_VAR_NAME: 'someValueHere'
49+
NAME: 'World'
5050
}
5151
});
5252
```
5353

5454
Any environment variables specified here will be available to the function at runtime.
5555

56-
Some environment variables are constant across all branches and deployments. But many environment values differ between deployment environments. [Branch-specific environment variables can be configured for Amplify hosting deployments](/gen2/deploy-and-host/fullstack-branching/secrets-and-vars/#set-environment-variables).
56+
Some environment variables are constant across all branches and deployments. But many environment values differ between deployment environments. [Branch-specific environment variables can be configured for Amplify hosting deployments](/[platform]/deploy-and-host/fullstack-branching/secrets-and-vars/).
5757

5858
Suppose you created a branch-specific environment variable in hosting called "API_ENDPOINT" which had a different value for your "staging" vs "prod" branch. If you wanted that value to be available to your function you can pass it to the function using
5959

60-
```ts title="amplify/functions/my-demo-function/resource.ts"
61-
export const myDemoFunction = defineFunction({
60+
```ts title="amplify/functions/say-hello/resource.ts"
61+
export const sayHello = defineFunction({
6262
environment: {
63+
NAME: "World",
6364
API_ENDPOINT: process.env.API_ENDPOINT
6465
}
6566
});
@@ -69,13 +70,13 @@ export const myDemoFunction = defineFunction({
6970

7071
Within your function handler, you can access environment variables using the normal `process.env` global object provided by the Node runtime. However, this does not make it easy to discover what environment variables will be available at runtime. Amplify generates an `env` symbol that can be used in your function handler and provides typings for all variables that will be available at runtime. Copy the following code to use it.
7172

72-
```ts title="amplify/functions/my-demo-function/handler.ts"
73+
```ts title="amplify/functions/say-hello/handler.ts"
7374
// highlight-next-line
74-
import { env } from '$amplify/env/my-demo-function'; // the import is '$amplify/env/<function name>'
75+
import { env } from '$amplify/env/say-hello'; // the import is '$amplify/env/<function name>'
7576

7677
export const handler = async (event) => {
77-
env. // the env object has intellisense for all environment variables that are available to the function
78-
return 'You made a function!';
78+
// the env object has intellisense for all environment variables that are available to the function
79+
return `Hello, ${env.NAME}!`;
7980
};
8081
```
8182

@@ -103,25 +104,33 @@ If you did not, you will need to manually configure your project. Within your `a
103104

104105
Sometimes it is necessary to provide a secret value to a function. For example, it may need a database password or an API key to perform some business use case. Environment variables should NOT be used for this because environment variable values are included in plaintext in the function configuration. Instead, secret access can be used.
105106

106-
Before using a secret in a function, you need to [define a secret](/gen2/deploy-and-host/fullstack-branching/secrets-and-vars/#set-secrets). After you have defined a secret, you can reference it in your function config.
107+
Before using a secret in a function, you need to [define a secret](/[platform]/deploy-and-host/fullstack-branching/secrets-and-vars/#set-secrets). After you have defined a secret, you can reference it in your function config.
107108

108-
```ts title="amplify/functions/my-demo-function/resource.ts"
109+
```ts title="amplify/functions/say-hello/resource.ts"
109110
import { defineFunction, secret } from '@aws-amplify/backend';
110111

111-
export const myDemoFunction = defineFunction({
112+
export const sayHello = defineFunction({
112113
environment: {
113-
API_KEY: secret('myApiKey') // this assumes you created a secret named "myApiKey"
114+
NAME: "World",
115+
API_ENDPOINT: process.env.API_ENDPOINT,
116+
API_KEY: secret('MY_API_KEY') // this assumes you created a secret named "MY_API_KEY"
114117
}
115118
});
116119
```
117120

118121
You can use this secret value at runtime in your function the same as any other environment variable. However, you will notice that the value of the environment variable is not stored as part of the function configuration. Instead, the value is fetched when your function runs and is provided in memory.
119122

120-
```ts title="amplify/functions/my-demo-function/handler.ts"
121-
import { env } from '$amplify/env/my-demo-function';
123+
```ts title="amplify/functions/say-hello/handler.ts"
124+
import { env } from '$amplify/env/say-hello';
122125

123126
export const handler = async (event) => {
124-
env.API_KEY; // this is the value of secret named "myApiKey"
125-
return 'You made a function!';
127+
const request = new Request(env.API_ENDPOINT, {
128+
headers: {
129+
// this is the value of secret named "MY_API_KEY"
130+
Authorization: `Bearer ${env.API_KEY}`
131+
}
132+
})
133+
// ...
134+
return `Hello, ${env.NAME}!`;
126135
};
127136
```

src/pages/[platform]/build-a-backend/functions/grant-access-to-other-resources/index.mdx

Lines changed: 88 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,33 @@ export function getStaticProps() {
2929
};
3030
}
3131

32-
When you grant a function access to another resource in your Amplify backend ([such as granting access to storage](/[platform]/build-a-backend/storage/#resource-access)), that will configure environment variables for that function to make SDK calls to the AWS services it has access to. Those environment variables are typed and available as part of the `env` object.
32+
In order for Amplify Functions to interact with other resources they must be given access. There are two ways to grant Amplify Functions access to other resources:
3333

34-
Example `defineStorage` that grants myDemoFunction access to files in `/foo/*`.
34+
1. [Using the `access` property](#using-the-access-property)
35+
2. [Using the AWS Cloud Development Kit (CDK)](#using-cdk)
36+
37+
## Using the `access` property
38+
39+
The `access` property is a property found in each of the `define*` functions for defining Amplify resources. It allows you specify the necessary actions using common language.
40+
41+
<Callout>
42+
43+
When you grant a function access to another resource in your Amplify backend ([such as granting access to storage](/[platform]/build-a-backend/storage/#resource-access)), it will configure environment variables for that function to make SDK calls to the AWS services it has access to. Those environment variables are typed and available as part of the `env` object.
44+
45+
</Callout>
46+
47+
Say you have a function that generates reports each month from your Data resource and needs to store the generated reports in Storage:
3548

3649
```ts title="amplify/storage/resource.ts"
37-
import { myDemoFunction } from '../functions/my-demo-function/resource';
50+
import { defineStorage } from '@aws-amplify/backend';
51+
import { generateMonthlyReports } from '../functions/generate-monthly-reports/resource';
3852

3953
export const storage = defineStorage({
40-
name: 'myProjectFiles',
54+
name: 'myReports',
4155
access: (allow) => ({
42-
'/foo/*': [allow.resource(demoFunction).to(['read', 'write', 'delete'])]
56+
'/reports/*': [
57+
allow.resource(generateMonthlyReports).to(['read', 'write', 'delete'])
58+
]
4359
})
4460
});
4561
```
@@ -48,19 +64,76 @@ This access definition will add the environment variable `myProjectFiles_BUCKET_
4864

4965
Here's an example of how it can be used to upload some content to S3.
5066

51-
```ts title="amplify/functions/my-demo-function/handler.ts"
52-
import { env } from '$amplify/env/my-demo-function';
67+
```ts title="amplify/functions/generate-monthly-reports/handler.ts"
5368
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
69+
import { env } from '$amplify/env/generate-monthly-reports';
5470

5571
const s3Client = new S3Client();
5672

57-
export const handler = async (event) => {
58-
await s3Client.send(
59-
new PutObjectCommand({
60-
Bucket: env.myProjectFiles_BUCKET_NAME,
61-
Key: 'foo/someFile.txt',
62-
Body: 'this is an example'
63-
})
64-
);
73+
export const handler = async () => {
74+
const command = new PutObjectCommand({
75+
Bucket: env.myReports_BUCKET_NAME,
76+
Key: `reports/${new Date().toISOString()}.csv`,
77+
Body: new Blob([''], { type: 'text/csv;charset=utf-8;' })
78+
});
79+
80+
await s3Client.send(command);
6581
};
6682
```
83+
84+
## Using CDK
85+
86+
When permissions are needed to access resources beyond the capabilities of the `access` property, you must use CDK.
87+
88+
Functions are created with an [_execution role_](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html), which is an IAM role that contains policies that dictate what resources your Function can interact with when it executes. This role can be extended using the [`addToRolePolicy()`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.IFunction.html#addwbrtowbrrolewbrpolicystatement) method:
89+
90+
```ts title="amplify/backend.ts"
91+
import { defineBackend } from "@aws-amplify/backend"
92+
import * as iam from "aws-cdk-lib/aws-iam"
93+
import * as sns from "aws-cdk-lib/aws-sns"
94+
import { weeklyDigest } from "./functions/weekly-digest/resource"
95+
96+
const backend = defineBackend({
97+
weeklyDigest,
98+
})
99+
100+
const weeklyDigestLambda = backend.weeklyDigest.resources.lambda
101+
102+
const topicStack = backend.createStack("WeeklyDigest")
103+
const topic = new sns.Topic(topicStack, "Topic", {
104+
displayName: "digest",
105+
})
106+
107+
// highlight-start
108+
const statement = new iam.PolicyStatement({
109+
sid: "AllowPublishToDigest",
110+
actions: ["sns:Publish"],
111+
resources: [topic.topicArn],
112+
})
113+
114+
weeklyDigestLambda.addToRolePolicy(statement)
115+
// highlight-end
116+
```
117+
118+
However some constructs provide a `grant*` method to grant access to common policy actions. Revisiting the example above you can grant the same access with `grantPublish`:
119+
120+
```ts title="amplify/backend.ts"
121+
import { defineBackend } from "@aws-amplify/backend"
122+
import * as iam from "aws-cdk-lib/aws-iam"
123+
import * as sns from "aws-cdk-lib/aws-sns"
124+
import { weeklyDigest } from "./functions/weekly-digest/resource"
125+
126+
const backend = defineBackend({
127+
weeklyDigest,
128+
})
129+
130+
const weeklyDigestLambda = backend.weeklyDigest.resources.lambda
131+
132+
const topicStack = backend.createStack("WeeklyDigest")
133+
const topic = new sns.Topic(topicStack, "Topic", {
134+
displayName: "digest"
135+
})
136+
137+
// highlight-next-line
138+
topic.grantPublish(weeklyDigestLambda)
139+
```

src/pages/[platform]/build-a-backend/functions/index.mdx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export function getStaticProps() {
3535

3636
<Callout warning>
3737

38-
**Under active development:** The Functions experience for Amplify Gen 2 is under active development. The experience may change between versions of `@aws-amplify/backend`. Try it out and provide feedback at https://github.com/aws-amplify/amplify-backend/issues/new/choose
38+
**Under active development:** The Functions experience for Amplify is under active development. The experience may change between versions of `@aws-amplify/backend`. Try it out and provide feedback at https://github.com/aws-amplify/amplify-backend/issues/new/choose
3939

4040
</Callout>
4141

src/pages/[platform]/build-a-backend/functions/modify-resources-with-cdk/index.mdx

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,27 @@ export function getStaticProps(context) {
2929
};
3030
}
3131

32+
Amplify Functions utilize the [`NodejsFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html) construct from the [AWS Cloud Development Kit (CDK)](https://aws.amazon.com/cdk/). The underlying resources can be modified, overridden, or extended using CDK after setting the resource on your backend.
33+
34+
```ts title="amplify/backend.ts"
35+
import { defineBackend } from '@aws-amplify/backend';
36+
import { myFunction } from './functions/my-function';
37+
38+
const backend = defineBackend({
39+
myFunction
40+
})
41+
42+
// CDK constructs can be accessed via
43+
backend.myFunction.resources
44+
45+
// where the Lambda function can be found on
46+
backend.myFunction.resources.lambda
47+
```
48+
49+
The Lambda resource available is a representation of [`IFunction`](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda.IFunction.html).
50+
3251
## Adding IAM Policies
3352

53+
To learn how to add IAM policies to a Function's execution role, visit the [documentation for granting access to other resources](/[platform]/build-a-backend/functions/grant-access-to-other-resources#using-cdk).
54+
3455
{/* ## Lambda Layers */}

0 commit comments

Comments
 (0)