threefoldtech / terraform-provider-grid

Apache License 2.0
8 stars 5 forks source link

How we can check payments for terraform deployments #176

Closed mhost39 closed 1 year ago

OmarElawady commented 2 years ago

Currently the contracts are available in the terraform.tfstate file. The contracts billing info should be available in graphql(?).

Can be added as a computed value to the resources.

rcmorano commented 2 years ago

I found contract ids are the values mapped to node ids in the node_deployment_id object from tfstate:

    {
      "mode": "managed",
      "type": "grid_network",
      "name": "k8s_network",
      _REDACTED_
      "provider": "provider[\"registry.terraform.io/threefoldtech/grid\"]",
      "instances": [
        {
          "schema_version": 0,
          _REDACTED_
          "attributes": {
            "node_deployment_id": {
              "xxx": 3204,
              "xxx": 3205,
              "xxx": 3206
            },
            _REDACTED_

Then you could use https://graphql.grid.tf/graphql to query your bills with a query similar to:

query myExpenses {
  contractBillReports(where: {contractID_gte: "3204", contractID_lte: "3209"}) {
    id
    amountBilled
    contractID
    discountReceived
    timestamp
  }
}
rcmorano commented 2 years ago

I'm using terragrunt, but you could adapt this script to terraform to get the total amounts billed per contract id; or just provide a $CONTRACTS_ARRAY variable:

#!/bin/bash

CONTRACTS_ARRAY=$(terragrunt run-all show -no-color -json 2> /dev/null | grep -v "INFO\|ERROR\|EOT" | jq '.values.root_module.resources[].values.node_deployment_id | to_entries[].value | tostring' 2>/dev/null | jq -cs | sed 's|"|\\"|g')

#CONTRACTS_ARRAY='[\"3047\", \"3048\", \"3049\", \"3050\", \"3051\", \"3052\"]'

cat > /tmp/$$.gql <<EOF
{ "query": "query MyQuery { contractBillReports(where: { contractID_in: ${CONTRACTS_ARRAY} }) { id amountBilled contractID discountReceived timestamp } }" }
EOF

curl -H 'Content-Type: application/json' -H 'Accept: application/json' \
  'https://graphql.grid.tf/graphql' \
  --data-binary @/tmp/$$.gql \
  -so /tmp/$$.gql.result.json

jq '.data.contractBillReports |
      def sum($k): group_by(.[$k])[]
      | map(.amountBilled | tonumber) as $billings
      | .[0] | . + {billedTotal: $billings | add }
      | del(.discountReceived, .amountBilled, .id, .timestamp);
      sum("contractID")' \
     /tmp/$$.gql.result.json