-1

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.
learning
  • 41
  • 3

2 Answers2

0

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.

guillaume blaquiere
  • 66,369
  • 2
  • 47
  • 76
0

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
user1934428
  • 19,864
  • 7
  • 42
  • 87