# Dynamically attach api key to usage plan

**URL:** <https://forum.serverless.com/t/dynamically-attach-api-key-to-usage-plan/4617>\
**Category:** Serverless Framework\
**Tags:** aws\
**Created:** [May 31, 2018, 1:19am UTC](https://forum.serverless.com/t/dynamically-attach-api-key-to-usage-plan/4617 "2018-05-31T01:19:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![logicminds](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/logicminds/32/2026_2.png) [@logicminds](https://forum.serverless.com/u/logicminds)\
**Post date:** [May 31, 2018, 1:19am UTC](https://forum.serverless.com/t/dynamically-attach-api-key-to-usage-plan/4617/1 "2018-05-31T01:19:37Z")

</div>

My lambda function creates api keys and I would like to attach them to a usage plan that is also generated by the cloudformation template where the function is defined. How can I pass in the id of the usage plan created by the serverless.yaml file since the usage plan ids are generated automatically.

```
function createUsageKey(key, plan_id) {
  return new Promise((resolve, reject) => {
  var params = {
  keyId: key.id /* required */,
  keyType: "API_KEY",
  usagePlanId: plan_id /* required */
};

apigateway.createUsagePlanKey(params, function(err, data) {
  if (err) {
    console.log(err, err.stack);
    reject(err);
  }
  // an error occurred
  else resolve(data); // successful response
});

```

});  
}

usagePlan:  
quota:  
limit: 1000  
offset: 2  
period: MONTH  
throttle:  
burstLimit: 20  
rateLimit: 10

---

<div class="post-metadata">

**Author:** ![buggy](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.serverless.com/buggy/32/177_2.png) [@buggy](https://forum.serverless.com/u/buggy)\
**Post date:** [May 31, 2018, 10:36am UTC](https://forum.serverless.com/t/dynamically-attach-api-key-to-usage-plan/4617/2 "2018-05-31T10:36:52Z")

</div>

The easiest solution is to pass the usage plan ID to the Lambda as an environment variable. You can set the value of the environment variable using a `Ref` in your `serverless.yml`.

Something like:

```auto
functions:
  myfunc:
    # The definition for your function here
    environment:
      USAGE_PLAN_ID: { "Ref": "MyUsagePlan" }

resources:
  Resources:
    MyUsagePlan:
      # Define your usage plan here

```

Then inside your Lambda use `process.env.USAGE_PLAN_ID`
