Creating a Security Group

Before we continue with Lambda functions' VPC configurations we also need to create a Security Group. Like network ACLs, Security Groups are logical security groups that you assign to your resources and you can allow or deny incoming or outgoing traffic. Contrary to ACL's, you assign security groups to resources, not to subnets. For our Lamba functions we do not specify any incoming traffic rule, because they cannot accept incoming traffic. However, we need to specify an outgoing traffic rule which will allow all traffic out. Let's add the following resource to your template:

"LambdaSecurityGroup": { 
  "Type": "AWS::EC2::SecurityGroup", 
  "Properties": { 
    "GroupDescription": "Security Group for Lambda Functions", 
    "VpcId": { 
      "Ref": "VPC" 
    }, 
    "SecurityGroupIngress": [ 
    ], 
    "SecurityGroupEgress": [ 
      { 
          "IpProtocol": "-1",
"FromPort": "0", "ToPort": "65535", "CidrIp": "0.0.0.0/0" } ] } }

After adding the security group config for each Lambda function you have, add this configuration to the Properties field:

"VpcConfig": { 
  "SecurityGroupIds": [ 
  { 
    "Ref": "LambdaSecurityGroup" 
  } 
], 
"SubnetIds": [ 
  { 
    "Ref": "PrivateSubnet1" 
  }, 
  { 
    "Ref": "PrivateSubnet2" 
  } 
] 

With this configuration, you tell AWS to run your Lambda function inside one of the subnets you specify and apply the indicated security group to its networking configuration.

After we deploy the stack, our application should still be running as expected, with one difference: the outgoing Internet requests now go through NAT Gateway. Maybe you did not realize, but actually our application heavily uses outgoing Internet connections because DynamoDB and CloudSearch APIs are in public internet, so without NAT Gateway and with VPC Config, our application would break.

Can you now try to register a user, then remove NAT Gateway, or basically Nat1Route and Nat2Route resources and make sure that when you remove routes your application doesn't work because it can't connect to AWS APIs?

Now you can navigate to the VPC page of AWS Console, click NAT Gateways, and see the Elastic IP addresses of your NAT Gateways:

These are the IP addresses that you need to tell your colleagues for allowing access. Now, your Lambda functions will be able to access that firewall-protected resource, and nobody else will.