Skip to content

Instantly share code, notes, and snippets.

@jamylak
Last active August 28, 2024 13:38
Show Gist options
  • Save jamylak/e310ebfefe92b623d9ed81f46d2ade0d to your computer and use it in GitHub Desktop.
Save jamylak/e310ebfefe92b623d9ed81f46d2ade0d to your computer and use it in GitHub Desktop.
AWS Lambda to Cloud Run
// This assumes you created a file with
// gcloud iam workload-identity-pools create-cred-config \
// projects/INSERT_PROJECT_NUMBER/locations/global/workloadIdentityPools/INSERT_POOL_ID/providers/INSERT_PROVIDER_ID \
// [email protected] \
// --aws \
// --output-file=testcreds.json
// Then you have passed GOOGLE_APPLICATION_CREDENTIALS=testcreds.json
// And you have gone through the rest of the federated auth setup eg.
// Pool / provider / sa / principalset / etc
// Note this is calling get() for cloud run
// Also seems SA requires `OpenID connect token creator`
async function main() {
// https://stackoverflow.com/a/77594859/1219006
const projectId = 'INSERT_PROJECT_ID_HERE';
const targetAudience = 'INSERT_CLOUD_RUN_URL_HERE';
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
targetAudience: targetAudience,
projectId: projectId,
});
const client = await auth.getClient();
const accessTokenResponse = await client.getAccessToken();
const accessToken = accessTokenResponse?.token;
if (!accessToken) {
throw new Error('accessToken not present');
}
const serviceAccountEmail = client.getServiceAccountEmail();
const getServiceTokenData = {
audience: targetAudience,
};
const getServiceTokenHeaders = {
'Content-Type': 'text/json',
Authorization: `Bearer ${accessToken}`,
};
const getServiceTokenConfig = {
headers: getServiceTokenHeaders,
};
console.log('Getting service token');
// this is simply the call from https://cloud.google.com/docs/authentication/get-id-token#external-idp , written in JS
const getServiceTokenResponse = await axios.post(
`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${serviceAccountEmail}:generateIdToken`,
getServiceTokenData,
getServiceTokenConfig,
);
console.log('Call cloud run');
const idToken = getServiceTokenResponse.data.token;
const resp = await axios.get(targetAudience, {
headers: {
Authorization: `Bearer ${idToken}`,
},
});
console.log('We did it!');
console.log(resp);
}
@jamylak
Copy link
Author

jamylak commented Aug 28, 2024

Note this is calling get() for cloud run

@jamylak
Copy link
Author

jamylak commented Aug 28, 2024

So far OpenID connect token creator is needed for the SA used to call cloud run it seems

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment