Using IAM Authentication With AWS VPC Lattice

Vinayak Pandey
2 min readMay 28, 2024

--

In this post, we’ll see how we can use IAM authentication with AWS VPC Lattice services.

Reference: https://onecloudplease.com/blog/exploring-amazon-vpc-lattice

https://github.com/curl/curl/issues/11007
https://docs.aws.amazon.com/vpc-lattice/latest/ug/sigv4-authenticated-requests.html#sigv4-authenticated-requests-python

Step 1: Deploy the cloudformation template given in https://onecloudplease.com/blog/exploring-amazon-vpc-lattice and test OutboundLambdaFunction which should be working fine.

Step 2: Now we’ll enable IAM authentication for the VPC lattice service. For that, add following permission to the IAM role of OutboundLambdaFunction.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "vpc-lattice-svcs:Invoke",
"Resource": "*"
}
]
}

and go to VPC lattice service->select the service->Access and set AWS IAM as Auth type. Specify following policy(specify the value for OutboundLambdaFunction ARN and Lattice Service ARN)

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "<OutboundLambdaFunction ARN>"
},
"Action": "vpc-lattice-svcs:Invoke",
"Resource": "<Lattice Service ARN>/*",
"Condition": {
"StringEquals": {
"vpc-lattice-svcs:RequestMethod": "GET"
}
}
}
]
}

Step 3: Now create a t3.medium EC2 instance with Amazon Linux2 AMI and follow https://computingpost.medium.com/how-to-install-python-3-10-on-amazon-linux-2-43ddcd511784 to install Python 3.10

Step 4: Follow https://docs.aws.amazon.com/lambda/latest/dg/python-package.html to create a deployment package for Lambda.Install botocore,requests and awscrt package(python3.10 -m pip install — target ./package botocore requests awscrt) and for Lambda, use following code(replace <LATTICE_SERVIVE_DNS> and <REGION>) for OutboundLambdaFunction

import os
import requests
import botocore.session
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials

def handler(event, context):
session = botocore.session.get_session()
headers = {"content-type": "application/json"}
endpoint = "https://<LATTICE_SERVIVE_DNS>"
method = "GET"
request = AWSRequest(method=method, url=endpoint, data="", headers=headers)
request.context["payload_signing_enabled"] = False

sigv4 = SigV4Auth(session.get_credentials(), "vpc-lattice-svcs", '<REGION>')
sigv4.add_auth(request)
prepped = request.prepare()
response = requests.get(prepped.url, headers=prepped.headers)
return response.json()

Make sure the zip file name is lambda_function.zip and upload the zip to Lambda.

Change lambda runtime to Python 3.10 and set the handler to lambda_function.handler

Now trigger the OutboundLambdaFunction and it will be working fine.

--

--