Search code examples
google-cloud-platformgoogle-compute-enginestartupscript

How do I ensure GCP start-script uses the correct service account?


I am creating a VM in GCP's Compute Engine with a service account that has permissions to read from a particular Cloud Storage bucket that contains some common configuration that may contain sensitive information, such as TLS certs. However when my startup script is executed, it is denied permission to access the bucket because it is using the Google Compute Engine default service account, not the service account I provisioned my VM to use. Can someone please help me figure out how to ensure that the startup script uses the right service account?

============= EDIT =============

Not sure how helpful this will be, but here is the puppet code that is failing, I can't/won't provide all of the puppet code. The actual startup script that is invoked when the instance starts is sudo puppet apply --verbose /opt/puppet/manifests/opensearch.pp >/var/log/puppetlabs/puppet/startup.log 2>&1. Note that I've already confirmed that puppet is not doing anything special with the service accounts. However puppet always uses the default service account, and fails to download the certs. If I SSH into the instance and run the same command by hand it works every time.

      exec { 'download_ssl_certs':
        command => "/snap/bin/gsutil cp -r gs://${opensearch::secrets_bucket}/${opensearch::cluster}/* ${opensearch::opensearch_path}/config/",
        notify  => Exec['ssl_certs_chown']
      }

      exec { 'ssl_certs_chown':
        command     => "/bin/chown -R ${opensearch::service_user}:${opensearch::service_group} ${opensearch::opensearch_path}/config",
        onlyif      => "/bin/ls -lhR ${opensearch::opensearch_path}/config | /bin/grep -i root | grep -v ${opensearch::service_user}",
        refreshonly => true,
        notify => Service['opensearch'],
      }

Solution

  • Example:

    gcloud compute instances create example-vm \
        --service-account [email protected] \
        --scopes https://www.googleapis.com/auth/cloud-platform 
    

    Creating and enabling service accounts for instances

    As the service account are part of metadata, you can access to metadata using startup scripts.

    Accessing metadata from a Linux startup script