Search code examples
terraformterraform-provider-gcp

Upload spring-boot jar into GCE Instance using terraform


What is the best way copying some-spring-boot.jar into GCE Instance?

I thought this is quite a common task, but after googling found zero documentation about it.

I have already generated service account in GCP and saved all the stuff into gcp-credentials.json :

{
  "type": "service_account",
  "project_id": "some project",
  "private_key_id": "someid",
  "private_key": "some key",
  "client_email": "[email protected]",
  "client_id": "xxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxdeveloper.gserviceaccount.com"
}

Here is what I'm doing after googling for hours:

terraform {
    required_providers {
        google = {
            source = "hashicorp/google"
        }
    }
}

provider "google" {
    version = "3.5.0"
    credentials = file("gcp-credentials.json")
    project = "some project"
    zone = "us-central1-a"
}

resource "google_compute_instance" "vm_instance" {
    name = "my-instance"
    machine_type = "e2-medium"
    #metadata_startup_script = file("startup.sh")

    tags = [
        "http-server",
        "https-server"]

    boot_disk {
        initialize_params {
            image = "some image with jdk"
        }
    }

    network_interface {
        network = "default"
        access_config {}
    }

    provisioner "file" {
        source = "../../../target/my-jar-1.0.0.jar"
        destination = "/tmp/my-jar-1.0.0.jar"

        connection {
            type = "ssh"
            user = "root"
            private_key = file("gcp-credentials.json").private_key
            agent = "false"
        }
    }
}

Whenever I run it says

[ERROR] Error: Missing required argument
[ERROR] 
[ERROR]   on main.tf line 43, in resource "google_compute_instance" "vm_instance":
[ERROR]   43:         connection {
[ERROR] 
[ERROR] The argument "host" is required, but no definition was found.

Any help will be really appreciated


Solution

  • Not tested (also I have never used Terraform towards GCP), try:

    host = self.network_interface.0.network_ip
    

    Line of thought:

    • the host indeed seems required (as per docs for connection)
    • the same docs hint on the special self variable:

    Expressions in connection blocks cannot refer to their parent resource by name. Instead, they can use the special self object.

    The self object represents the connection's parent resource, and has all of that resource's attributes.

    • rest is my guess how to get an IP address from a GCP instance