'Assign Terraform output to a variable within Jenkins Pipeline

I am creating an EC2 instance using aws_cloudformation_stack and capturing it's output for private_ip. I want to use this output within my jenkins pipeline so that I can assign it to a variable and then inject that variable into my ansible vars file.

I am having a lot of trouble assigned the value of the terraform output to my private_ip variable in jenkins.

Is something like this possible in terraform or should I be working with a template file instead?

TF code :

resource "aws_cloudformation_stack" "test_instance" {
  ...
}

output "test_instance_private_ip" {
  value = aws_cloudformation_stack.test_instance.outputs.PrivateIp
}

Jenkins pipeline code :

def private_ip
stage('terraform'){
  sh """
    terraform init
    terraform plan
    terraform apply --auto-approve
  """
  private_ip = sh(returnStdout: true, script: "terraform output test_instance_private_ip").trim()
}

stage('ansible') {
  sh """
    ansible-playbook -i inventory.yml --limit testgroup -e "private_ip=${private_ip}" playbook.yml -v
  """
}

Current output :

Warning: No outputs found
Warning: Empty or non-existent state


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source