Using Python wrapper with Terraform

Posted: February 13, 2018 in Amazon Web Services (AWS), Linux, terraform

python-terraform is a python module provide a wrapper of terraform command line tool.More details here

Installation is simple:

pip install python-terraform

Now we can use python script to interact with terraform. In this example we’ll pass number of instances as variable to python script and new instances will be created

Python script



enter = int(input('Enter number of instances: '))

from python_terraform import *
tf = Terraform(working_dir='/home/ja/terraform/demo-3', variables={'count':enter})
tf.plan(no_color=IsFlagged, refresh=False, capture_output=True)
approve = {"auto-approve": True}



count is variable name specified in file, enter is variable specified in python script to which we’ll pass number of instances interactively

Because enter variable is variable, single quotes had to be removed, otherwise, quotes needs to be put around that variable also


Running script above will spin-up as many instances as we specified at prompt:



Files in /home/ja/terraform/demo-3 folder

resource "aws_instance" "example" {
  ami = "${lookup(var.AMIS, var.AWS_REGION)}"
  instance_type = "t2.micro"


tags {

 output "ime" {
   value = ["${aws_instance.example.*.tags.Name}","${aws_instance.example.*.public_ip}"]
} (variable file)


variable "AWS_ACCESS_KEY" {

variable "count" {

variable "AWS_SECRET_KEY" {
variable "AWS_REGION" {
  default = "eu-west-1"
variable "AMIS" {
  type = "map"
  default = {
    us-east-1 = "ami-13be557e"
    us-west-2 = "ami-06b94666"
    eu-west-1 = "ami-844e0bf7"


provider "aws" {
    access_key = "${var.AWS_ACCESS_KEY}"
    secret_key = "${var.AWS_SECRET_KEY}"
    region = "${var.AWS_REGION}"


  1. Ike Kim says:

    when I try the above I get this error after I enter the number of instances. “No configuration files found!\n\nPlan requires configuration to be present. Planning without a configuration\nwould mark everything for destruction, which is normally not what is desired.”

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s