Fedor  Petrov
Fedor Petrov

Reputation: 1050

How to execute scripts (remote-exec) under Google Cloud Container Optimized OS using Terraform

I know that container optimized OS is mostly "noexec". I have a usecase when I need to execute some simple scripts in my home directory, copy files from my docker image to host etc. There are no problems with this when I log into the instance with SSH. But with terraform it seems not to work:

resource "null_resource" "test_upload2" {

    count = length(var.nodes)

    provisioner "remote-exec" {
        connection {
            type     = "ssh"
            host     = google_compute_address.static[count.index].address
            private_key = file("keys/private_key")
            user     = var.admin_username
            script_path = "/home/hyperledger/provision.sh"
        }

        inline = [
        "ls"
        ]
    
    }
    depends_on = [google_compute_instance.peer-blockchain-vm, null_resource.test_upload]

}

I get the following error message:

null_resource.test_upload[0] (remote-exec): bash: /home/hyperledger/provision.sh: Permission denied


Error: error executing "/home/hyperledger/provision.sh": Process exited with status 126

Is there a way to perform this purely with Terraform? Seems not nice to outsource this logic to some local shell script and achieve the goal with "local-exec".

Upvotes: 2

Views: 1951

Answers (1)

Fedor  Petrov
Fedor Petrov

Reputation: 1050

For now I've found a solution. When I create the instance I set the following startup-script:

resource "google_compute_instance" "my_vm" {
...
metadata_startup_script = "mkdir -p /home/hyperledger/tmp/;sudo mount -t tmpfs -o size=100M tmpfs /home/hyperledger/tmp/" 
}

It creates an in-memory disk. The script-path in resource should then be redefined as follows:

script_path = "/home/hyperledger/tmp/provision.sh"

All scripts in this temporary directory can be executed.

The first executed provisioner should should change the owner of home directory since it was created with root owner above:

    provisioner "remote-exec" {
            connection {
                type     = "ssh"
                private_key = file(var.private_key)
                user     = var.admin_username
                script_path = "/home/hyperledger/tmp/provision.sh"
            }

            inline = [
            "sudo chown -R hyperledger:hyperledger /home/hyperledger"
            ]
        }

Upvotes: 3

Related Questions