Skip to content

title: CloudSlash - Drift Surgery Reference description: Your Terraform says the instance should be t3.medium. The cloud says t3.large. Rosetta finds the exact file, exact line, exact commit that caused the drift: ...


Drift Surgery

Your Terraform says the instance should be t3.medium. The cloud says t3.large. Rosetta finds the exact file, exact line, exact commit that caused the drift: and patches it.

Warning

Reconciling physical cloud divergence against a declarative IaC configuration is conventionally a manual process, prone to human error. The Drift Surgeon algorithm in pkg/engine/drift/ calculates and applies remediation paths directly into the Terraform state file using monotonic serial assertions.


The Drift Calculation

Drift is the relative complement of the declared state \(D\) with respect to the physical state \(P\):

\[ \text{Drift} = P \setminus D \]

If the Deviation Engine finds a node \(n \in P\) with a valid CRN but no mapped association in the AST Compilation pass (see HCL AST Compilation), \(n\) is marked with a Drift exception.

In-Memory State Mutability

A standard terraform refresh synchronizes physical attributes down to the local state file blindly, frequently masking out-of-band architectural changes permanently. Drift Surgery takes the opposite approach: it forcefully aligns physical infrastructure to the declared AST baseline.

To do this safely without corrupting the .tfstate array, we manipulate the state payload with optimistic concurrency control:

// pkg/engine/drift/surgeon.go

func (s *Surgeon) ExciseNode(ctx context.Context, tfState []byte, targetCRN string) ([]byte, error) {
    var state TerraformStatePayload
    if err := json.Unmarshal(tfState, &state); err != nil {
        return nil, err
    }

    // Isolate and excise target
    var cleanResources []Resource
    for _, res := range state.Resources {
        if generateCRN(res) != targetCRN {
            cleanResources = append(cleanResources, res)
        }
    }

    state.Resources = cleanResources

    // Increment strict monotonic serial to enforce ordering
    state.Serial = state.Serial + 1

    return json.Marshal(state)
}

Atomic State Push

To prevent concurrent drift surgeries from racing against each other, CloudSlash asserts an If-Match ETag check against the remote state backend (e.g., AWS S3):

func (s *Surgeon) AtomicPush(ctx context.Context, bucket, key string, newState []byte, expectedETag string) error {
    _, err := s.s3Client.PutObject(&s3.PutObjectInput{
        Bucket:  aws.String(bucket),
        Key:     aws.String(key),
        Body:    bytes.NewReader(newState),
        IfMatch: aws.String(expectedETag),
    })
    return err
}

If the ETag check fails: meaning another daemon pushed a state change between the read and write: the API rejects the mutation. The Drift Surgeon yields to Swarm, which starts exponential backoff and kicks off a fresh recalculation against the new state.