user3442473
user3442473

Reputation: 303

How to pass variable from jenkins to terraform

I created a small project on GitHub with which I create an ec2 with tomcat on aws and assign it the policies relating to port 8080. Now I would like to take a small step forward and

  1. wait for the server to be active to be able to copy files
  2. copy some sample files (such as index.html + a jpg) in the Tomcat ROOT folder.

The problem is that I can't pass the PEM file to the terraform part of the code. I saw some examples that put the PEM file on the git repository but I don't want to do this and I uploaded the PEM file in the Jenkis credentials. What is the correct way to "wait" for the server to be ready and then copy the files?

Jenkins:

environment {

    AWS_ACCESS_KEY_ID     = credentials('AWS_ACCESS_KEY_ID')
    AWS_SECRET_ACCESS_KEY = credentials('AWS_SECRET_ACCESS_KEY')
    USER_KEYPEM      = credentials("AWS_USER_KEY_PEM")
}

terraform side

resource "aws_instance" "web1" {
   ami           = "${lookup(var.ami_id, var.region)}"
   instance_type = "t2.micro"
   vpc_security_group_ids = ["sg-XXXXXXXXX"]

    tags = {
    Name = "myFirstWebServer"
  }

    provisioner "remote-exec" {
    inline = [
      "cloud-init status --wait"
    ]
  }
    provisioner "file" {
    source      = "web/index.html"
    destination = "/path_to_tomcat_root/index.html"
  }
    provisioner "file" {
    source      = "web/img.jpg"
    destination = "/path_to_tomcat_root/img.jpg"
  }

    connection {
    user        = "ec2-user"
    private_key = "?????????"    <-----how to pass pem file from Jenkins credentials?
    host = "${aws_instance.web1.public_ip}"
  }

Upvotes: 0

Views: 1619

Answers (1)

user3442473
user3442473

Reputation: 303

I solved in this way

In Jenkins stored pem_key_file

 TF_VAR_private_key_file = credentials('MY_KEY_PAIR_PEM')

...

 export TF_VAR_private_key_file;

In terraform

connection {
user        = "ec2-user"
private_key = "${file("${var.private_key_file}")}"
host = "${aws_instance.web1.public_ip}"
agent = false
timeout = "3m"

Upvotes: 1

Related Questions