Lambda Python to Query SSM Parameter Store Value - python

I want to write a Python 3.6 query in AWS Lambda to get details on an AWS SSM parameter store but I get a null response. If I query via AWS CLI I get the details on the parameter store item including the AMI ID which is my ultimate goal. The parameter store path is:
/aws/service/ami-windows-latest/Windows_Server-2019-English-Core-Base-2019.07.12
My code is below, any insight into why this is not returning the expected results would be greatly appreciated.
import json
import boto3
def lambda_handler(event, context):
client = boto3.client('ssm')
response=client.get_parameters(Names=['/aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base']),
#return "Success"
print (response)
I'm expecting the same output that I get when I run the following AWS CLI command.
aws ssm get-parameters --names /aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base --region us-east-1

I figured this out with the help of a co-worker with more Python experience. The code is below.
import boto3
client = boto3.client('ssm')
def lambda_handler(event, context):
parameter = client.get_parameter(Name='/aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base', WithDecryption=True)
print(parameter)
return parameter ['Parameter']['Value']

Worth checking your lambda has enough permissions to interact with aws SSM. Just for the initial checking i would suggest give full access by using policy policy/AmazonSSMFullAccess
Lambda IAM role should have the above policy.
docs aws boto3 docs

You can use this library which has error handling out-of-the-box:
AWStanding
from awstanding.parameter_store import load_parameters
LOOKUP_DICT = {
'/aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base': 'CONVENIENT_NAME'
}
load_parameters(LOOKUP_DICT)
os.environ.get('CONVENIENT_NAME')
The advantage here is that you can easily load a lot of parameters with minimmum overhead.

Related

how to read tags associated to AWS Lambda function?

I'm trying to read the tags associated to AWS lambda function using boto3 API with python
import boto3
client = boto3.client('lambda')
response = client.list_tags(Resource=arn)
when I test the above code from lambda function , i see network API error.Is there any way to read the tags from context ? I appreciate your help.
set your client variable as:
client = boto3.client('lambda',
aws_access_key_id=Awscred.aws_access_key_id,
aws_secret_access_key=Awscred.aws_secret_access_key,
region_name=Awscred.region_name)
this worked for me

sqs boto3: The address 'https://us-west-2.queue.amazonaws.com/xxxx/my-name' is not valid for this endpoint

I'm having a very hard time trying to find out how to correctly configure sqs in boto3 to be able to send messages to my sqs queue. It looks like there is some confusion around boto3 and legacy endpoints but I'm getting the error message The address 'https://us-west-2.queue.amazonaws.com/xxxx/my-name' is not valid for this endpoint. for each permutation of the config I can imagine. Here's the code.
# Tried both of these
sqs_queue_url = 'https://sqs.us-west-2.amazonaws.com/xxxx/my-queue'
sqs_queue_url = 'https://us-west-2.queue.amazonaws.com/xxxx/my-queue'
# Tried both of these
sqs = boto3.client("sqs", endpoint_url="https://sqs.us-west-2.amazonaws.com")
sqs = boto3.client("sqs")
# _endpoint updates
logger.info("sqs endpoint: %s", sqs._endpoint)
# Keeps failing
sqs.send_message(QueueUrl=sqs_queue_url, MessageBody=message_json)
I'm hoping this is a silly mistake. What config am I missing?
From docs, AWS CLI and Python SDK use legacy endpoints:
If you use the AWS CLI or SDK for Python, you can use the following legacy endpoints.
Also, when you set endpoint you need to add https:
sqs = boto3.client("sqs", endpoint_url="https://us-west-2.queue.amazonaws.com")

boto3 lambda script to shutdown RDS not working

I'm just starting out with boto3 and lambda and was trying to run the below function via Pycharm.
import boto3
client = boto3.client('rds')
response = client.stop_db_instance(
DBInstanceIdentifier='dummy-mysql-rds'
)
But i receive the below error:
botocore.errorfactory.DBInstanceNotFoundFault: An error occurred (DBInstanceNotFound) when calling the StopDBInstance operation: DBInstance dummy-mysql-rds not found.
Do you know what may be causing this?
For the record, I have the AWS toolkit installed for Pycharm and can run simple functions to list and describe ec2 instances and my AWS profile has admin access.
By explicitly defining the profile name the below function now works via Pycharm. Thank you #OleksiiDonoha for your help in getting this resolved.
import boto3
rds = boto3.setup_default_session(profile_name='dev')
client = boto3.client('rds')
response = client.stop_db_instance(
DBInstanceIdentifier='dev-mysql-rds'
)

Can't access 'event' properties when calling it in Lambda Function in AWS

I have a specific issue on my AWS lambda function that I have recently built (in python 3.8). It's supposed to support a post request and put an item from the body of the request into a table in DynamoDB.
My Lambda function looks like this:
When I test using API Gateway it works perfectly and I get what I expect.
and the item gets inserted into the table. This is the response on the API-Gateway Test:
Here's my API gateway post method set up:
However, when I use postman and try to post a JSON I get this Key Error: (Note the JSON body of the post is identical).
Any help I get here will be very much appreciated.
Edit: For those who have read the comments below. This is the code I'm using to return the event:
So I believe I solved the issue. I simply un-ticked the 'use lambda proxy integration' box when setting up the post method in API Gateway. Now I'm receiving the body as the event as I wanted. Thank you for your responses anyway.
def handler(event, context):
requestObject = ""
if "requestObject" in event:
requestObject = event["requestObject"]
else:
requestJson = json.loads(event["body"])
if "requestObject" in requestJson:
serialNumber = requestJson["requestObject"]

Where would I receive http request in AWS

Am beginner to Amazon web services.
I have a below lambda python function
import sys
import logging
import pymysql
import json
rds_host=".amazonaws.com"
name="name"
password="123"
db_name="db"
port = 3306
def save_events(event):
result = []
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name,
connect_timeout=30)
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute("select * from bodyPart")
result = cur.fetchall()
cur.close()
print ("Data from RDS...")
print (result)
cur.close()
bodyparts = json.dumps(result)
bodyParts=(bodyparts.replace("\"", "'"))
def lambda_handler(event, context):
save_events(event)
return bodyParts
using an above function am sending json to the client using API gateway, now suppose user selects an item from the list and send it back, in form of json where will i get http request and how should i process that request
I just made an additional information for #Harsh Manvar.
The easiest way I think is you can use
api-gateway-proxy-integration-lambda
Currently API Gateway support AWS lambda very good, you can pass request body (json) by using event.body to your lambda function.
I used it everyday in my hobby project (a Slack command bot, it is harder because you need to map from application/x-www-form-urlencoded to json through mapping template)
And for you I think it is simple because you using only json as request and response. The key is you should to select Integratiton type to Lambda function
You can take some quick tutorials in Medium.com for more detail, I only link the docs from Amazon.
#mohith: Hi man, I just made a simple approach for you, you can see it here.
The first you need to create an API (see the docs above) then link it to your Lambda function, because you only use json, so you need to check the named Use Lambda Proxy integration like this:
Then you need to deploy it!
Then in your function, you can handle your code, in my case, I return all the event that is passed to my function like this:
Finally you can post to your endpoint, I used postman in my case:
I hope you get my idea, when you successfully deployed your API then you can do anything with it in your front end.
I suggest you research more about CloudWatch, when you work with API Gateway, Lambda, ... it is Swiss army knife, you can not live without it, it is very easy for tracing and debug your code.
Please do not hesitate to ask me anything.
you can use aws service called API-gateway it will give you endpoint for http api requests.
this api gateway make connection with your lambda and you can pass http request to lambda.
here sharing info about creating rest api on lambda you can check it out : https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-create-api.html
aws also provide example for lambda GET, POST lambda example.you just have to edit code it will automatically make api-gateway.as reference you can check it.
From Lambda Console > create function > choose AWS serverless repository > in search bar type "get" and search > api-lambda-dynamodb > it will take value from user and process in lambda.
here sharing link you can direct check examples : https://console.aws.amazon.com/lambda/home?region=us-east-1#/create?tab=serverlessApps

Categories

Resources