import { execCmdAndParseJson , execCmdWithExitOnFailure } from './cmd-utils' ; import { isCelotoolHelmDryRun } from './helm_deploy' ; import { switchToGCPProject , switchToProjectFromEnv } from './utils' ; export async function createServiceAccountIfNotExists ( name , gcloudProject ? , description ? ) { if ( gcloudProject !== undefined ) { await switchToGCPProject ( gcloudProject ) ; } else { await switchToProjectFromEnv ( ) ; } const serviceAccounts = await execCmdAndParseJson ( `gcloud iam service-accounts list --filter "displayName:${ name }" --quiet --format json` ) ; const serviceAccountExists = serviceAccounts . some ( ( account ) => account . displayName === name ) ; if ( ! serviceAccountExists ) { let cmd = `gcloud iam service-accounts create ${ name } --display-name="${ name }" ` ; if ( description ) { cmd = cmd . concat ( `--description="${ description }"` ) ; } if ( isCelotoolHelmDryRun ( ) ) { console . info ( `This would run the following command:\n${ cmd }\n` ) ; } else { await execCmdWithExitOnFailure ( cmd ) ; } } return ! serviceAccountExists ; } export async function getServiceAccountEmail ( serviceAccountName ) { const [ output ] = await execCmdWithExitOnFailure ( `gcloud iam service-accounts list --filter="displayName<=${ serviceAccountName } AND displayName>=${ serviceAccountName }" --format='value[terminator=""](email)'` ) ; return output ; } export function getServiceAccountKey ( serviceAccountEmail , keyPath ) { return execCmdWithExitOnFailure ( `gcloud iam service-accounts keys create ${ keyPath } --iam-account ${ serviceAccountEmail }` ) ; } export async function setupGKEWorkloadIdentities ( serviceAccountName , gcloudProjectName , kubeNamespace , kubeServiceAccountName ) { if ( ! serviceAccountName . includes ( 'gcp' ) ) { return ; } const serviceAccountEmail = await getServiceAccountEmail ( serviceAccountName ) ; const roleIamWorkloadIdentityUserCmd = `gcloud iam --project ${ gcloudProjectName } service-accounts add-iam-policy-binding \
  --role roles/iam.workloadIdentityUser \
  --member "serviceAccount:${ gcloudProjectName }.svc.id.goog[${ kubeNamespace }/${ kubeServiceAccountName }]" \
  ${ serviceAccountEmail }` ; if ( isCelotoolHelmDryRun ( ) ) { console . info ( `This would run the following: ${ roleIamWorkloadIdentityUserCmd }\n` ) ; } else { await execCmdWithExitOnFailure ( roleIamWorkloadIdentityUserCmd ) ; } }