metadata: version: "1" dependencies: apps: - id: dynatrace.automations version: ^1.946.2 inputs: [] workflow: title: Account Cost Reporting tasks: token_data_upload: name: token_data_upload description: Build a custom task running js Code action: dynatrace.automations:run-javascript input: script: >- import { execution } from '@dynatrace-sdk/automation-utils'; import { credentialVaultClient } from '@dynatrace-sdk/client-classic-environment-v2' export default async function ({ execution_id }) { // Function to upload the JSON data to the blob storage async function uploadJsonFileToBlob(payload, docName) { try { const response = await fetch(`${blobUrl}/${docName}?${sasToken}`, { method: "PUT", headers: { "x-ms-blob-type": "BlockBlob", // Specify the blob type "x-ms-version": "2020-04-08", // API version "Content-Type": "application/json", // Set the content type to JSON "Content-Length": payload.length.toString() // Set content length }, body: payload // Send the JSON data as the request body }); if (response.ok) { console.log(`JSON file ${docName} uploaded successfully to Blob Storage!`); } else { console.error(`Failed to upload ${docName} JSON file. Status:`, response.status, response.statusText); } } catch (error) { console.error("Error during upload:", error); } } // Function to get cost data async function getCostData(url) { const dataHeaders = new Headers(); dataHeaders.append("Authorization", `Bearer ${token}`); const dataOptions = { method: "GET", headers: dataHeaders, redirect: "follow" }; const dataResponse = await fetch(url, dataOptions); const dataResult = await dataResponse.json(); let jsonString = JSON.stringify(dataResult); return jsonString; } /*=============================================================================================*/ // Variables const ex = await execution(execution_id); const env = ""; const now = (new Date().toISOString()); const newNow = encodeURIComponent(now); const contractStartDate = ""; // Example:2024-01-01T00%3A00%3A00.000Z const blobSasKey = await credentialVaultClient.getCredentialsDetails({ id: '' }); const oauthCredentials = await credentialVaultClient.getCredentialsDetails({ id: '' }); // Cost Endpoint variables const DATA_URL = "https://api.dynatrace.com/sub/v2/accounts"; const accountId = ""; const subscriptionId = ""; const BASE_URL = `${DATA_URL}/${accountId}/subscriptions/${subscriptionId}`; // Define variables for your storage account, container, and blob const accountName = ""; const containerName = ""; const sasToken = blobSasKey.token; const blobUrl = `https://${accountName}.blob.core.windows.net/${containerName}`; // Array of endpoints const endpoints = [ { url:`${DATA_URL}/${accountId}/subscriptions/forecast`, docName:`${env}_forecast.json`}, { url:BASE_URL, docName:`${env}_subscription.json`}, { url:`${BASE_URL}/environments/usage?startTime=${contractStartDate}&endTime=${newNow}`, docName:`${env}_usage.json`}, { url:`${BASE_URL}/cost`, docName:`${env}_cost.json`}, { url:`${BASE_URL}/environments/cost?startTime=${contractStartDate}&endTime=${newNow}`, docName:`${env}_cost_capability.json`}, ]; /*=============================================================================================*/ // Get bearer token // Headers const myHeaders = new Headers(); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); // Body const urlencoded = new URLSearchParams(); urlencoded.append("grant_type", "client_credentials"); urlencoded.append("client_id", oauthCredentials.username); urlencoded.append("client_secret", oauthCredentials.password); urlencoded.append("resource", `urn:dtaccount:${accountId}`); urlencoded.append("scope", "account-uac-read"); const requestOptions = { method: "POST", headers: myHeaders, body: urlencoded, redirect: "follow" }; const TOKEN_URL = "https://sso.dynatrace.com/sso/oauth2/token"; const tokenResponse = await fetch(TOKEN_URL, requestOptions); const tokenResult = await tokenResponse.json(); const token = tokenResult.access_token; /*=============================================================================================*/ // Loop through each endpoint to get cost reports for (const endpoint of endpoints) { // Call the function to get cost data let costData = (await getCostData(endpoint.url)); // Call the function to upload the JSON file data to Blob Storage uploadJsonFileToBlob(costData, endpoint.docName); } return { triggeredBy: ex.trigger }; } position: x: 0 y: 1 predecessors: [] description: "" trigger: schedule: rule: null trigger: type: time time: 02:00 timezone: America/New_York isActive: true isFaulty: false nextExecution: 2024-10-24T06:00:00.000Z filterParameters: earliestStart: 2024-10-16 inputs: {} schemaVersion: 3