Can terraform tf file or module automatically expire resources?

Multi tool use
Multi tool use


Can terraform tf file or module automatically expire resources?



In cloudformation you can set a TTL on a stack that runs a command which deletes the stack: https://aws.amazon.com/blogs/devops/scheduling-automatic-deletion-of-application-environments/



How do I do this in a TF file?



OR maybe I could have a script that gets the create time of a tf file (the state file), compare that with the current time and do a destroy? that might work too





Cloudformation itself doesn't have a way of self terminating at some specific time. That link shows a Cloudformation template that creates an instance that tears down the stack using at to run a script to delete the stack at a specific time. You could use the same principle with Terraform as long as your Terraform config created an instance with permissions and configuration to be able to do that.
– ydaetskcoR
Jul 2 at 13:09



at




1 Answer
1



Terraform does not keep track of these sorts of lifecycle events. It doesn't look like the state file even has data about when it was updated (except for whatever metadata the backend has, such as file creation/update time). I would suggest keeping track of this data yourself and model the lifecycle outside of terraform.



Here is an example of how to manage this lifecycle using SSM parameter store to keep this state.



First, I generate a unique identifier for the "stack" (to borrow a CloudFormation term) and store the create time in SSM Parameter Store. We pass in this UUID to Terraform for tagging and backend configuration


#!/bin/bash
set -e

UUID=$(uuidgen)
TIMESTAMP=$(date +%s)
SSM_PARAMETER_STORE_NAME="/terraform/created_at/${UUID}"
<configure terraform backend config>
<terraform apply step>
aws ssm put-parameter --name "$SSM_PARAMETER_STORE_NAME" --value "$TIMESTAMP" --type String > /dev/null
echo $UUID



Then you can use something like the following to conditionally destroy stack $UUID if it has been created $threshold seconds ago.


$UUID


#!/bin/bash

usage(){
echo "Performs terraform destroy if a terrafrom 'stack' was created at least <threshold> seconds ago"
echo "Usage: $0 UUID threshold"
exit 1
}

validate_args(){
[[ -z "$1" ]] && { echo "No UUID passed, exiting" ; usage; exit 1; }
[[ -z "$2" ]] && { echo "No Threshold passed, exiting" ; usage; exit 1; }
echo "Args validated"
}

check_time(){
SSM_PARAMETER_STORE_NAME=$1
THRESHOLD=$2
NOW=$(date +%s)

CREATED_AT=$(aws ssm get-parameter --name "$SSM_PARAMETER_STORE_NAME" | jq -r .Parameter.Value)
if [[ $(($NOW - $CREATED_AT)) > $THRESHOLD ]]; then
echo "Threshold not met, exiting"
exit 1
fi
echo "Threshold met"
}

perform_tf_destroy(){
<configure terraform backend config>
<terraform destroy step>
aws ssm delete-parameter --name "$SSM_PARAMETER_STORE_NAME"
}

validate_args $1 $2
SSM_PARAMETER_STORE_NAME="/terraform/created_at/${1}"
THRESHOLD=$2
check_time $SSM_PARAMETER_STORE_NAME $THRESHOLD
perform_tf_destroy



You could then automate periodically performing that check for every UUID in /terraform/created_at/*


/terraform/created_at/*





I do not think this works like that: terraform destroy -auto-approve -var "UUID=${1}". can you point terraform directly to a state file and have it destroy like that? I think not because you need to do a terraform init first which means you need to configure the backend in a tf file somewhere and have it initialise to the right State file which is a big mess.
– red888
Jul 1 at 21:30





Indeed, those were how things worked in my test environment. Depending what backend you're using, yours will be different. For example, your backend might be configured like so: terraform init -backend-config 'bucket=${BUCKET}' -backend-config 'region=${REGION}' -backend-config 'dynamodb_table=${TABLE}' -backend-config 'key=${UUID}.state' , after which you could terraform apply -var 'UUID=${UUID}' to bring up the stack using the UUID var to disambiguate resources that require names (if you so chose).
– Eric Johnson
Jul 1 at 22:00



terraform init -backend-config 'bucket=${BUCKET}' -backend-config 'region=${REGION}' -backend-config 'dynamodb_table=${TABLE}' -backend-config 'key=${UUID}.state'


terraform apply -var 'UUID=${UUID}'


UUID





The point was to wrap whatever you need to do in Terraform with code that manages 1) a name for the stack that you can reference later, 2) records the create time, and 3) can be called periodically to compare the current time against the create time and destroy if a threshold is exceeded.
– Eric Johnson
Jul 1 at 22:05


destroy





that doesnt really work either, run that terraform init command in an empty dir and terraform doesnt pull down the state or anything. it succeeds but its disconnected from that actual state file. If you run "terraform state list" after that command you get nothing. The only way I could get init to work was with an actual tf file- also you need to specify the "provider" as well. This means dynamically generating a tf file and writing to disk (let me know if there is a better way). My point is having to script this is pretty terrible.
– red888
Jul 1 at 22:19





If I could just point directly to a state file (all with command line args) and destroy it that might work, but doesnt seem possible
– red888
Jul 1 at 22:19






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

cUKPg9Qb sTAw,FO1,lm,LN x140 F2l1eb8,5wKBbiu2Cup8,a9BU U Qd52OFpCkkYI6DAEFcH4 Qxt52vuRHIj
Z yffgS0bSr4URTUxofP 0pEP2K MmLGzvR4A

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

Audio Livestreaming with Python & Flask