Backwardation25
Backwardation25

Reputation: 167

AWS boto3 Config Service list of EC2s with states

I would like to use Boto3 to generate a list of EC2s along with state changes (pending, running, shutting-down, terminated etc.) between a set of two date times. My understanding is that Config Service maintains histories of EC2s even if the EC2 no longer exists. I have taken a look at this document, however I am having difficulty understanding which functions to use in order to accomplish the task at hand.

Thank you

Upvotes: 0

Views: 962

Answers (1)

Madhukar Mohanraju
Madhukar Mohanraju

Reputation: 2863

Under the assumption that you have already configured AWS Config rules to track ec2-instance state, this approach will suit your need.

1) Get the list of ec2-instances using the list_discovered_resources API.Ensure includeDeletedResources is set to True if you want to include deleted resources in the response.

response = client.list_discovered_resources(
    resourceType='AWS::EC2::Instance',
    limit=100,
    includeDeletedResources=True,
    nextToken='string'
)

Parse the response and store the resource-id.

2) Pass each resource_id to the get_resource_config_history API.

response = client.get_resource_config_history(
    resourceType='AWS::EC2::Instance',
    resourceId='i-0123af12345be162h5',      // Enter your EC2 instance id here
    laterTime=datetime(2018, 1, 7),         // Enter end date. default is current date.
    earlierTime=datetime(2018, 1, 1),       // Enter start date
    chronologicalOrder='Reverse'|'Forward',
    limit=100,
    nextToken='string'
)

You can parse the response and get the state changes, which ec2 instance went through for that corresponding time period.

Upvotes: 1

Related Questions