pythonamazon-web-serviceslambdaaws-event-bridgeaws-ssm

SSM execution not working via lambda if instance id is not hardcoded


I want to fetch the instance id from the eventbridge rule for every newly launched instances and execute the ssm doc via lambda. Below is the code, this code is not executing ssm document for the newly launched instance. But I'm getting proper instance_id of the newly launched instance.

import boto3
import json

def lambda_handler(event, context):
    # Extract the instance ID from the event (assuming it's already extracted as shown in your previous code)
    if event.get("detail", {}).get("eventName") == "RunInstances":
        # Extract the instance ID and event details
        instance_id = event["detail"]["responseElements"]["instancesSet"]["items"][0]["instanceId"]
        event_details = json.dumps(event["detail"], indent=2)

        # You can now process the instance ID and event details as needed
        print(f"{instance_id}")
        # print(f"Event Details:\n{event_details}")

    return {
        "statusCode": 200,
        "body": json.dumps("Event processed successfully")
    }


    # Initialize the SSM client
    ssm_client = boto3.client('ssm')
    # instance_id = 'i-08be0407d47363235' # hard-code for example

    # Define the SSM document name and parameters
    document_name = "prisma-cloud-agent-ssm-doc"  # Replace with your SSM document name
    ssm_parameters = {
        "InstanceId": [instance_id],
        # Add more parameters as needed
    }

    try:
        # Send the command using the SSM document and parameters
        response = ssm_client.send_command(
            InstanceIds=[instance_id],
            DocumentName=document_name,
            Parameters=ssm_parameters,
        )

        # Process the response as needed
        command_id = response["Command"]["CommandId"]
        print(f"SSM Command sent with Command ID: {command_id}")

        return {
            "statusCode": 200,
            "body": json.dumps(f"SSM Command sent with Command ID: {command_id}")
        }
    except Exception as e:
        print(f"Error sending SSM command: {str(e)}")
        return {
            "statusCode": 500,
            "body": json.dumps("Error sending SSM command")
        }

But not executing SSM doc for this newly launched instance.

But if I'm hardcoding the instanceid as below. This is working and executing SSM doc for the below hardcoded instance id. I have commented the other field to fetch the instanceid here

import boto3
import json

def lambda_handler(event, context):
    # Extract the instance ID from the event (assuming it's already extracted as shown in your previous code)
    # if event.get("detail", {}).get("eventName") == "RunInstances":
    #     # Extract the instance ID and event details
    #     instance_id = event["detail"]["responseElements"]["instancesSet"]["items"][0]["instanceId"]
    #     event_details = json.dumps(event["detail"], indent=2)

    #     # You can now process the instance ID and event details as needed
    #     print(f"{instance_id}")
    #     # print(f"Event Details:\n{event_details}")

    # return {
    #     "statusCode": 200,
    #     "body": json.dumps("Event processed successfully")
    # }


    # Initialize the SSM client
    ssm_client = boto3.client('ssm')
    instance_id = 'i-08be0407d47363235' # hard-code for example

    # Define the SSM document name and parameters
    document_name = "xyz-doc"  # Replace with your SSM document name
    ssm_parameters = {
        "InstanceId": [instance_id],
        # Add more parameters as needed
    }

    try:
        # Send the command using the SSM document and parameters
        response = ssm_client.send_command(
            InstanceIds=[instance_id],
            DocumentName=document_name,
            Parameters=ssm_parameters,
        )

        # Process the response as needed
        command_id = response["Command"]["CommandId"]
        print(f"SSM Command sent with Command ID: {command_id}")

        return {
            "statusCode": 200,
            "body": json.dumps(f"SSM Command sent with Command ID: {command_id}")
        }
    except Exception as e:
        print(f"Error sending SSM command: {str(e)}")
        return {
            "statusCode": 500,
            "body": json.dumps("Error sending SSM command")
        }

What would be the reason for not working this in the first code without hardcoding?

I'm getting proper output as cloudwatch logs with instance_id as below

Instance ID: i-006aba8d1200a8bce

Solution

  • Your code is not actually issuing the SSM send command because of the earlier return statement which shortcuts the Lambda function handler:

    return {
        "statusCode": 200,
        "body": json.dumps("Event processed successfully")
    }