skip to Main Content

Here is what I am doing:
gcloud compute instances create example-instance --image-family $image --image-project $projectID --machine-type $type_machine --metadata startup-script='#!/bin/bash mkdir -p ~/test'

This look super simple. The instance is created no test folder is created in home directory. I checked the VM logs I can’t find anything.
So this means we can not create a folder in home directory with GCP VM startup script?
Or is there any thing I am missing?

  1. Checked the VM logs but didnt find anything.
  2. Was manually able to create folder in home directory after the VM is created.

2

Answers


  1. According to your script and to the logs, your folder is correctly created in the home folder.

    But the home folder of which user?? You are using a path shortcut ~/ but for who?

    In the documentation, it’s mentioned that the startup script is launched as "root" user. When you, user "Learning", ssh to the VM, a /home/learning/ home directory is created.

    And it’s obviously not the same as the root user.

    Login or Signup to reply.
  2. I don’t know how gcloud executes the start script, but a reasonable assumption is that it runs it using sh.

    Your startup script starts with a comment character. Therefore, the whole line is treated as a comment and nothing gets executed. The #! would make sense as a pseudo comment as the first line in a script file (which is different from your case), but even then, the mkdir would have to be in the subsequent line.

    However, even removing the #! would not help in your example, for the following reason:

    If you run bash foo bar baz, bash executes the command foo as bash-script and passes to it the parameters bar and baz. In your case, the command is mkdir, and this is not a bash script, but a binary executable. You would get the error message

    mkdir: cannot execute binary file
    

    Therefore, the solution would be to use the -c option and write

    /usr/bin/bash -c 'mkdir -p ~/test'
    

    as "start script". The -c tells bash to interpret the following argument as a statement to be executed.

    BTW: If gcloud really understands the start-script argument as sh command, you don’t need bash at all and can simply use

    mkdir -p $HOME/test
    

    Since it is most likely that the start script is executed with the working directory set to what glcoud considers your home, you should be able to do just a

    mkdir -p test
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search