Latest Dynatrace
AWS EC2 offers a wide range of instance types optimized for different use cases, enabling appropriate scaling of cloud resources. Often, such instances are left running or stopped but never terminated, increasing recurring costs. The AWS Connector action called EC2: Terminate instances can automatically terminate such instances based on highly customizable conditions.
This page is intended for cloud engineers looking for a mechanism to terminate already-stopped AWS EC2 instances automatically.
You'll learn how to set up and run a workflow with the EC2: Terminate instances action to terminate already stopped AWS EC2 instances.
To set up a workflow to terminate already stopped AWS EC2 instances
On the Workflows overview page, select
Workflow.
Select the default title Untitled Workflow, and copy and paste the workflow title Terminate every stopped AWS EC2 instance.
In the Select a trigger panel, select the trigger type On Demand.
Select Add task on the trigger node.
Add the EC2: Describe Instances action.
EC2
.list-stopped-instances
. This action will fetch all instances that are stopped currently:instance-state-code
and value 80
to filter for stopped instances.Add a Run JavaScript action, and rename it to extract-instanceids
. This action will perform data mapping for the subsequent actions.
In the Input tab, add the following code
import { execution } from '@dynatrace-sdk/automation-utils';import { executionsClient, actionExecutionsClient } from '@dynatrace-sdk/client-automation';export default async function ({ execution_id, action_execution_id }) {const item = (await actionExecutionsClient.getActionExecution({ id: action_execution_id })).loopItem['reservations']const instanceIds = item.Instances.map(instance => instance.InstanceId);return { InstanceIds: instanceIds };}
In the Options tab
reservations
.{{ result("list-stopped-instances").Reservations }}
.Add the EC2: Terminate instances action, and rename it to terminate-instances
. This action will terminate the instances that were returned in the previous step.
{{ _.instances.InstanceIds }}
.instances
.{{ result("extract-instanceids") }}
.Add an EC2: Create tags action, and rename it to create-termination-date-tag
. This action will add a tag to the instances with the time of termination.
{{ _.instances.InstanceIds }}
.Termination_date
and the value {{ now() }}
.instances
.{{ result("extract-instanceids") }}
.Select Save.
Select Run.
Now, you can save costs by using a Dynatrace workflow that automatically terminates every stopped AWS EC2 instance.