> ## Documentation Index
> Fetch the complete documentation index at: https://docs.formae.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Deploy a Lambda

> An AWS infrastructure pattern, deployed with formae.

A VPC-bound Lambda function that reads its dependencies from environment
variables instead of hardcoded values. One forma reconciles the foundation (a
VPC with private subnets, security groups, an IAM execution role, S3 buckets,
and an RDS Postgres database), and a second forma patches in the function once
its deployment package is in the deployment bucket. The function's environment
variables resolve to the database endpoint and bucket names at apply time.

```mermaid theme={"languages":{"custom":["/languages/pkl.json"]}}
flowchart LR
  target["aws-target"]:::tgt

  subgraph stack["simple-lambda-stack"]
    direction LR
    vpc["VPC"]:::res
    igw["Internet gateway"]:::res
    subnets["Private subnets"]:::res
    lambdaRole["Lambda role"]:::res
    dbSg["Database security group"]:::res
    lambdaSg["Lambda security group"]:::res
    deployBucket["Deployment bucket"]:::res
    dataBucket["Data bucket"]:::res
    dbSubnetGroup["DB subnet group"]:::res
    database["RDS Postgres"]:::res
    fn["Lambda function"]:::res

    vpc --> igw
    vpc --> subnets
    vpc --> dbSg
    vpc --> lambdaSg
    subnets --> dbSubnetGroup
    dbSg --> database
    dbSubnetGroup --> database
    lambdaRole --> fn
    database --> fn
    dataBucket --> fn
    deployBucket --> fn
    lambdaSg --> fn
    subnets --> fn
  end

  target --> stack

  classDef tgt fill:#FF8201,stroke:#B25900,color:#ffffff
  classDef res fill:#FFF3E6,stroke:#FF8201,color:#02024B
  style stack fill:#ffffff,stroke:#02024B,stroke-width:2px,stroke-dasharray:6 4,color:#02024B
```

**Deploy.** First reconcile the foundational infrastructure. Then, once the
deployment package is uploaded to the deployment bucket, patch in the function:

```bash theme={"languages":{"custom":["/languages/pkl.json"]}}
formae apply --mode reconcile \
  /opt/pel/formae/examples/formae-plugin-aws/lambda-env/apply_infra.pkl

formae apply --mode patch \
  /opt/pel/formae/examples/formae-plugin-aws/lambda-env/patch_lambda.pkl
```

**Verify.** Once the function is applied, it is under management:

```bash theme={"languages":{"custom":["/languages/pkl.json"]}}
formae inventory resources --query="type:AWS::Lambda::Function"
```

**Tear down.** Remove the function first, then the foundation:

```bash theme={"languages":{"custom":["/languages/pkl.json"]}}
formae destroy \
  /opt/pel/formae/examples/formae-plugin-aws/lambda-env/patch_lambda.pkl

formae destroy \
  /opt/pel/formae/examples/formae-plugin-aws/lambda-env/apply_infra.pkl
```

The full forma is in the
[lambda-env example](https://github.com/platform-engineering-labs/formae-plugin-aws/tree/main/examples/lambda-env).
