user1247196
user1247196

Reputation: 191

Using Terraform as an API

I would like to use Terraform programmatically like an API/function calls to create and teardown infrastructure in multiple specific steps. e.g reserve a couple of eips, add an instance to a region and assign one of the IPs all in separate steps. Terraform will currently run locally and not on a server.

I would like to know if there is a recommended way/best practices for creating the configuration to support this? So far it seems that my options are:

  1. Properly define input/output, heavily rely on resource separation, modules, the count parameter and interpolation.
  2. Generate the configuration files as JSON which appears to be less common

Thanks!

Upvotes: 3

Views: 2571

Answers (1)

Preston Martin
Preston Martin

Reputation: 2963

Instead of using Terraform directly, I would recommend a 3rd party build/deploy tool such as Jenkins, Bamboo, Travis CI, etc. to manage the release of your infrastructure managed by Terraform. Reason being is that you should treat your Terraform code in the exact same manner as you would application code (i.e. have a proper build/release pipeline). As an added bonus, these tools come integrated with a standard api that can be used to execute your build and deploy processes.

If you choose not to create a build/deploy pipeline, your other options are to use a tool such as RunDeck which allows you to execute arbitrary commands on a server. It also has the added bonus of having a excellent privilege control system to only allow specified users to execute commands. Your other option could be to upgrade from the Open Source version of Terraform to the Pro/Premium version. This version includes an integrated GUI and extensive API.

As for best practices for using an API to automate creation/teardown of your infrastructure with Terraform, the best practices are the same regardless of what tools you are using. You mentioned some good practices such as clearly defining input/output and creating a separation of concerns which are excellent practices! Some others I can recommend are:

  1. Create all of your infrastructure code with idempotency in mind.
  2. Use modules to separate the common shared portions of your code. This reduces the number of places that you will have to update code and therefore the number of points of error when pushing an update.
  3. Write your code with scalability in mind from the beginning. It is much simpler to start with this than to adjust later on when it is too late.

Upvotes: 1

Related Questions