Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a packer variable from a terraform state

Working with openstack. I have a two steps process to build images with packer: (1) create infrastructure using terraform basically, just a network routed to the internet and some security group that allows SSH (2) build the image using packer

Problem is I need to provide the id of the network built by terraform to packer. I can do this manually by checking the state file but I was wondering what was the best practice to automate this?

like image 489
julien forgeat Avatar asked Jan 26 '23 19:01

julien forgeat


2 Answers

You can use terraform output to read outputs from the state. You can pass these on as Packer variables, i.e.

packer build -var network=$(terraform output network_uuid) template.json
like image 69
Rickard von Essen Avatar answered Jan 31 '23 14:01

Rickard von Essen


Another suggestion: you can call Packer from Terraform.

resource "null_resource" "packer_runner" {
  triggers = {
    install_script = "${sha1(file("${path.module}/scripts/app/install.sh"))}"
    packer_file    = "${sha1(file("${path.module}/packer/packer.json"))}"
  }

  provisioner "local-exec" {
    working_dir = "${path.module}"
    command     = "packer build -var 'ami_name=${var.ami_name}' -var 'aws_region=${var.aws_region}' -var 'network_id=${var.network_id}' -var -parallel-builds=1 ./packer/packer.json"
    interpreter = ["PowerShell", "-Command"]
  }
}

Then, on packer.json:

<...stuff...>
  "provisioners": [
    {
      "type": "shell",
      "inline": "/usr/bin/cloud-init status --wait"
    },
    {
      "type": "shell",
      "environment_vars": [
        "NETWOR_ID={{user `network_id`}}"
      ],
      "script": "./scripts/app/install.sh"
    },
<...more stuff...>
like image 30
cfelipe Avatar answered Jan 31 '23 13:01

cfelipe