How to Trigger Terraform from AWS Lambda Function?


I am thinking of automating a small task in my personal dev AWS account. I have a working Terraform script and it does what I want. The only problem is that I have to remember to destroy else I end up paying a good amount to AWS. It would be great if I had a Lambda which will stop/start the terraform script ( basically - terraform apply and terraform destroy )as I can schedule my Lambda easily. This also help me in improving my knowledge as well ( I know it may not be a recommended solution).

Really APPRECIATE if someone could help me with some starters code/ideas .


Yes that’s doable. Setup a lambda triggered by a time based Cloudwatch event, store your state in something like S3 and then have the code run the “terraform destroy” command. You’d need to ensure you include the terraform binary in the lambda code and have the right permissions attached to be able to access the state bucket & perform changes.

Thanks @stuart-c . I can setup the lambda with appropriate IAM permissions. I can keep the state file with all the configs in S# ( no problem until now). However, How will the lambda access the Terraform binaries – I am unable to process.

Appreciate your guidance here.

You need to include the Terraform binary in the bundle that you are uploading to the lambda.

So for example if you were creating your lambda in Python you’d include your Python code, and libraries and the Terraform binary.

I was wondering if you could point me to some starter’s code OR share your code if you have done. I have done something similar using CloudFormation but don’t want to convert my Terraform to CloudFormation now. Something like the below link will be very helpful.