1

I am trying to create an AWS Lambda function that creates a file and then uploads it into S3.

The AWS CLI commands would be:

aws ec2 describe-network-interfaces --output table > report.csv
aws s3 cp report.csv s3://testec2lambd

Is there anyway that I can use AWS CLI within my Lambda function?

Alternatively, how do I write it in the function as a python script?

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
Mohamad
  • 19
  • 1
  • Don't use CLI in your code. Use boto3. There are lots of examples on how to read and write files to S3 using boto3. – RodP Sep 06 '22 at 21:18
  • https://stackoverflow.com/questions/71941335/uploading-an-xml-file-to-a-s3-bucket-with-boto3/71961753#71961753 – RodP Sep 06 '22 at 21:19

1 Answers1

0

Rather than calling the AWS CLI from an AWS Lambda function, you can do all operations within the Lambda function. For example:

import boto3
import pprint

# Describe Network Interfaces
ec2_client = boto3.client('ec2')

response = ec2_client.describe_network_interfaces()

# Save it to a local file
pretty_print_json = pprint.pformat(response).replace("'", '"')

with open('/tmp/output_file', 'w') as f:
    f.write(pretty_print_json)

# Upload file to S3
s3_client = boto3.client('s3')

s3_client.upload_file('/tmp/output_file', 'mybucket', 'mykey')
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470