# Roll out cost ownership with Terraform

By the end of this guide, each team's place in Costfluent is a Terraform module: the team and its workspace access, the segment and rule that give it its cost, its budget, and a report delivered to it on a schedule, with the workspace's tag policy beside them. Every change to who owns what is then a reviewed pull request. It is for the platform engineer who runs Terraform for the organization, and for the engineering lead who reviews it. The path goes from a token and the provider, through one module per team, to the tag policy and the objects that already exist. Each step links to the page that owns the detail.

## Before you start

- Terraform, and a state backend that is encrypted with restricted access: the state holds a channel's `config`, which carries its recipients, in plaintext. See [How it behaves](/developers/terraform#how-it-behaves).
- The ID of the workspace the teams' cost is read in, starting with `wsp_`, and for each team its name, product, cost centre, the cloud accounts it owns, its monthly amount and who receives its report.
- Creating the token needs the access [Terraform](/developers/terraform#before-you-start) names; see [Access model](/concepts/access-model).
- The steps create objects and do not depend on the [sample data](/quickstart#sample-data), but nothing is sent from it, so the report in step 6 is delivered only once a real connection has replaced it.

## 1. Create a token for Terraform

Under **Settings**, then **API tokens**, create a token from **Read and write** and also select the **Users, teams and channels** group, which `costfluent_team`, `costfluent_team_workspace_access` and `costfluent_app` need. Keep it out of source control: pass it in `COSTFLUENT_API_KEY`, filled from your pipeline's secret store. See [Create a token](/developers/terraform#create-a-token).

## 2. Configure the provider

Pin the provider to a minor version: until version 1.0, a new minor version may need changes to your configuration. See [Configure the provider](/developers/terraform#configure-the-provider).

```hcl
terraform {
  required_providers {
    costfluent = {
      source  = "costfluent/costfluent"
      version = "~> 0.8.0"
    }
  }
}

provider "costfluent" {}
```

## 3. Give the team its workspace access

Steps 3 to 6 write one team's objects. Keep them in a module of your own, with the values in angle brackets as its variables, and call it once per team: a new team is then one more module call. The team gets `canView` on the workspace here, and `canEdit` grants edit access instead; see [Access model](/concepts/access-model). Add its members with `costfluent_team_member`, or under **Members** on the team. Every member is also on the Everyone team, so a team's grant limits no one until the workspaces are restricted. See [Grant workspace access](/admin/users-teams-and-roles#grant-workspace-access).

```hcl
resource "costfluent_team" "this" {
  name = "<team name>"
}

resource "costfluent_team_workspace_access" "this" {
  team_id      = costfluent_team.this.id
  workspace_id = "<workspace ID>"
  access_level = "canView"
}
```

## 4. Assign the team its cost

A segment names the team, its product and its cost centre, and receives cost only once a rule assigns some to it. The rule here claims the cost of the team's accounts by their **Sub-account**; any filter a report takes works, such as a tag. Where two teams' rules could claim the same cost, `priority` decides, the lower first. See [Segments and allocation rules](/allocation/segments).

```hcl
resource "costfluent_segment" "this" {
  workspace_id = "<workspace ID>"
  team_id      = costfluent_team.this.id
  product      = "<product>"
  cost_centre  = "<cost centre>"
}

resource "costfluent_allocation_rule" "this" {
  workspace_id = "<workspace ID>"
  name         = "<rule name>"
  filter       = jsonencode([{ field = "SubAccount", operator = "In", values = ["<account ID>"] }])
  segment_id   = costfluent_segment.this.id
}
```

## 5. Put a budget on the team

A budget on the segment counts the team's direct cost and its share of shared cost, what a report filtered to the segment counts. `amount` is a decimal string, the same for every month. See [Budgets](/planning/budgets).

```hcl
resource "costfluent_budget" "this" {
  workspace_id = "<workspace ID>"
  name         = "<budget name>"
  amount       = "<monthly amount>"
  currency     = "<currency>"
  segment_id   = costfluent_segment.this.id
}
```

## 6. Deliver the team's report

A segment created through Terraform arrives without the report and the weekly digest one made in the product gets, so the module saves a report filtered to the segment and schedules it monthly to the team's email channel. See [Filter a report to a segment](/allocation/segments#filter-a-report-to-a-segment) and [Share and schedule reports](/cost-reports/share-and-schedule).

```hcl
resource "costfluent_cost_report" "this" {
  workspace_id  = "<workspace ID>"
  title         = "<report title>"
  date_interval = "LastMonth"
  group_by      = [{ dimension = "ServiceName" }]
  filter        = "costs.segment = '${costfluent_segment.this.id}'"
}

resource "costfluent_app" "this" {
  key    = "email"
  name   = "<channel name>"
  config = jsonencode({ recipients = "<email address>" })
}

resource "costfluent_cost_report_subscription" "this" {
  workspace_id   = "<workspace ID>"
  cost_report_id = costfluent_cost_report.this.id
  name           = "<schedule name>"
  schedule_type  = "monthly"
  app_ids        = [costfluent_app.this.id]
}
```

## 7. State the workspace's tag policy

A workspace has one tag policy, replaced whole on every apply, and creating the resource replaces any policy the workspace already has. So it belongs in the root configuration once per workspace, not in the team's module. A `rule` can name a team's accounts under `account_ids` to require more of them. Costfluent measures cost against the policy and changes nothing in your cloud accounts. See [Set a tag policy](/allocation/tags#set-a-tag-policy).

```hcl
resource "costfluent_tag_policy" "workspace" {
  workspace_id = "<workspace ID>"

  rule {
    required_keys = ["<tag key>"]
  }
}
```

## 8. Bring existing objects under Terraform

A team, segment, rule, budget or report made in the product comes under Terraform without being created again: write its resource in the module, then import it with an `import` block in the root configuration whose `to` names the resource inside the team's module, such as `module.checkout.costfluent_segment.this`. The import ID depends on the resource, such as `<workspace ID>:<object ID>` for a segment, and a tag policy's is the workspace's ID. Run `terraform plan` and change the configuration until it shows no difference, unless you mean to change the object. See [Bring existing objects under Terraform](/developers/terraform#bring-existing-objects-under-terraform).

## Check the result

- After the apply, `terraform plan` shows no changes.
- Under **Settings**, then **Teams**, each team's **Workspace access** lists the workspace.
- On **Segments**, each team has its segment and its rule, and **Budgets** lists each team's budget.
- Each team's report lists its schedule under **Existing schedules** as **Active**.

## Keep it true

- A change made in the product to an object Terraform manages shows as drift on the next plan, and an object deleted in the product is created again. Costfluent recommends changing these objects in code only, once they are there.
- Costfluent recommends adding a team, an account or a new owner as a change to the module calls, so the pull request is the record of who owns what.

## Related

- [Terraform](/developers/terraform), [Segments and allocation rules](/allocation/segments) and [Users, teams and roles](/admin/users-teams-and-roles)
- [Cost as code: budgets, tags and exports in Terraform](https://costfluent.com/handbook/tooling/apis-terraform-and-cost-as-code), on keeping cost controls in a repository
- [Put cost controls on a new cloud account](/guides/cost-controls-for-a-new-account)
