Search code examples
google-cloud-platformgoogle-deployment-manager

How to Execute a Command Line script on a VM Instance When Updating a Deployment Manager Deployment


I currently have this configuration in my vm.yaml file, which sets up a vm instance that allows http requests and serves a custom Hello World! page, as specified in the startup-scripts section:

resources:
- type: compute.v1.instance
  name: quickstart-deployment-vm
  properties:
    zone: us-central1-f
    machineType: https://www.googleapis.com/compute/v1/projects/my_project/zones/us-central1-f/machineTypes/f1-micro
    disks:
      ...
    networkInterfaces:
      ...
    tags:
        items: ["http"]

    metadata:
      items:
      - key: startup-script
        value: |
          #!/bin/bash
          apt-get update
          apt-get install -y apache2
          echo '<!doctype html><html><body><h1>Hello World!</h1></body></html>' | sudo tee /var/www/html/index.html

- type: compute.v1.firewall
  name: tcp-firewall-rule
  properties:
    targetTags: ["http"]
    network: https://www.googleapis.com/compute/v1/projects/my_project/global/networks/default
    sourceRanges: ["0.0.0.0/0"]
    targetTags: ["http","http-server"]
    allowed:
     - IPProtocol: TCP
       ports: ["80"]

After running gcloud deployment-manager deployments create vm-deploy --config vm.yaml, I get the expected Hello World! response when accessing the vm's external ip. However, I now want to update this deployment to change the content of the response, let's say to What's up, everyone! However, it seems like I cannot do this simply by changing what is in the startup-scripts section. I tried putting this in a vm-update.yaml file:

resources:
- type: compute.v1.instance
  name: quickstart-deployment-vm
  properties:
    ...
    metadata:
      items:
      - key: startup-script
        value: |
          #!/bin/bash
          apt-get update
          apt-get install -y apache2
          echo '<!doctype html><html><body><h1>What's up, everyone!</h1></body></html>' | sudo tee /var/www/html/index.html

- type: compute.v1.firewall
  name: tcp-firewall-rule
  properties:
    ...

And ran gcloud deployment-manager deployments update vm-deploy --config vm-update.yaml. However, the response and the index.html file have not changed, and they are still Hello World!. I'm guessing this is because the startup-script is only executed upon instance creation, but not upon instance update. Does anyone know how I can execute a script on my vm with deployment manager, when I'm updating the vm?


Solution

  • One 'hack' I found was I could change the machineType of the VM in vm-update.yaml, which I believe forces the VM to be rebooted/reinitialized, and run the startup-script.