skip to Main Content

Everytime an EC2 instance gets created, I want to run a script on that instance. I understand this could be done using the user_data parameter but some of these instances get created manually so people may forget to fill in that parameter sometimes. I want to rely on something automatic instead.

I figured to do it with EventBridge, catch an event that would indicate me that an instance has been created then trigger a lambda that would run the script. But when looking in the documentation I couldn’t find any event that would relate to "EC2 created", see https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/monitoring-instance-state-changes.html.

Any idea how to get this done?

2

Answers


  1. Create an EventBridge rule with the following pattern to catch the event:

    {
      "source": ["aws.ec2"],
      "detail-type": ["AWS API Call via CloudTrail"],
      "detail": {
        "eventSource": ["ec2.amazonaws.com"],
        "eventName": ["RunInstances"]
      }
    }
    

    and configure the target of the rule to be an AWS lambda function. Configure the lambda to parse the event and invoke an SSM run command against the instance.

    Login or Signup to reply.
  2. In my case I have an EventBridge Rule with the following detail:

    {
      "detail-type": ["EC2 Instance State-change Notification"],
      "detail": {
        "state": ["running"]
      },
      "source": ["aws.ec2"]
    }
    

    And my target is a lambda function that runs an SSM document on that instance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search