7

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?

3 Answers3

10

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
Rickard von Essen
  • 4,110
  • 2
  • 23
  • 27
2

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...>
cfelipe
  • 327
  • 1
  • 9
1

Wanted to add it as a suggestion to the answer above but the edit queue was full. Adding it separately then.

If you need to pass all the variables from terraform output to packer's 'input':

packer build $(terraform output -json | jq -j -r 'to_entries[] | " -var \(.key)=\(.value | .value)"') template.pkr.hcl