DEV Community

Cover image for Day 94: A State File Is Not the Cloud and an Empty String That Deleted Something
Nnamdi Felix Ibe
Nnamdi Felix Ibe

Posted on AI-assisted

Day 94: A State File Is Not the Cloud and an Empty String That Deleted Something

Day 94 of DevOps, Day 44 of Azure. First Terraform task in the series, which closes the Ansible block at Days 82 to 93.

Both halves ask the same question in different words: a command succeeded, so what did it actually prove? Terraform's own state listing proves something narrower than it looks. An Azure patch step reported success while quietly deleting the placeholder it was supposed to fill in.

One Terraform task, one Azure task. A VPC, then a script on a VM that would not run. The tasks come from the KodeKloud Engineer platform.

Task 1: A VPC in Terraform

A VPC named devops-vpc, CIDR 10.0.0.0/16, in us-east-1.

Step 1: Reading what was already there

provider.tf and a README. The provider block and region were written for me, with a version constraint, so terraform init installed hashicorp/aws v5.91.0 rather than whatever is newest. That makes the whole build pinned and repeatable, and init writes .terraform.lock.hcl recording the choice. That file belongs in version control.

So main.tf was the only new file:

resource "aws_vpc" "devops-vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "devops-vpc"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Plan, then apply

Plan: 1 to add, 0 to change, 0 to destroy.
aws_vpc.devops-vpc: Creation complete after 1s [id=vpc-be9b655843a531502]
Enter fullscreen mode Exit fullscreen mode

Step 3: Two checks that are not the same check

terraform state list
# aws_vpc.devops-vpc

aws ec2 describe-vpcs --filters "Name=tag:Name,Values=devops-vpc" --region us-east-1
Enter fullscreen mode Exit fullscreen mode

This is the bit I want to pull out, because it is easy to run both and think of them as one verification.

terraform state list proves that Terraform's state file contains a resource called aws_vpc.devops-vpc. It makes no network call. It asserts nothing whatsoever about AWS. Delete the VPC from the console a minute later and that command prints exactly the same line.

The describe-vpcs call is the one that asks AWS, and it is what establishes the VPC exists with the right CIDR, the right tag and the right region.

Running both is correct and worth keeping as a habit. The Terraform-native version of the same idea is terraform plan against existing state, which refreshes from the provider before comparing, so "No changes" is a much stronger statement than a state listing. A difference between the two is called drift, and the plan is the thing that finds it.

Incidentally, the tag is not decoration. AWS has no name field on a VPC. The console's Name column is that tag, and the filter I verified with is a tag lookup. Without it, the only handle is a generated VPC ID, so the verification command could not have been written before the apply.

What the docs recommend

Terraform printed its own warning, and I walked past it:

Note: You didn't use the -out option to save this plan, so Terraform
can't guarantee to take exactly these actions if you run "terraform
apply" now.
Enter fullscreen mode Exit fullscreen mode

That is not boilerplate. A bare plan followed by a bare apply runs the planning step twice, against whatever the world looks like at each moment. The plan I reviewed is not the plan that executes.

On one resource in a lab, the difference is nothing. The habit is still the wrong one, because the shape that matters in a pipeline is:

terraform plan -out=tfplan
terraform apply tfplan
Enter fullscreen mode Exit fullscreen mode

apply with a saved plan executes exactly what was reviewed and does not prompt, because the approval happened at review time.

Two sub-second gates were missing too, and they are the same pattern I used on an ARM template a day earlier:

terraform fmt -check
terraform validate
Enter fullscreen mode Exit fullscreen mode

validate checks syntax and internal consistency without contacting a provider.

And two defaults got accepted rather than chosen. The provider docs give them: enable_dns_support "Defaults to true", enable_dns_hostnames "Defaults to false". The second has a consequence that surfaces much later. Instances in this VPC get a private DNS name and no public DNS hostname, which is different from the account's default VPC, where hostnames are on. It shows up as a missing PublicDnsName weeks after the VPC was built, and the fix is one line at creation time:

  enable_dns_hostnames = true
Enter fullscreen mode Exit fullscreen mode

One honest note about the environment

"OwnerId": "000000000000",
"DhcpOptionsId": "default",
Enter fullscreen mode Exit fullscreen mode

An all-zero account ID, and a DHCP options ID that is the literal word default where real AWS returns dopt- and an identifier. I am reading that as a mock AWS endpoint rather than the real thing, from those two fields.

Which changes what can be learned here. The Terraform configuration and the provider's behaviour are real. The API responses are approximations, so a field that looks odd in this output is not necessarily odd in AWS. Worth holding on to, because the Terraform block runs to Day 100.


Task 2: Getting a script on a VM to send to Event Hubs

A namespace with auto-inflate, an event hub, and a provided script run enough times that events show up in metrics.

Step 1: Reading the script first

connection_str = "<your_event_hub_connection_string>"
event_hub_name = "nautilus-hub"
producer = EventHubProducerClient.from_connection_string(...)
Enter fullscreen mode Exit fullscreen mode

Three decisions came out of one cat. It wants a connection string, not a managed identity, and az vm show confirmed identity: null, so SAS was the only route. The hub name is hardcoded. And from_connection_string with a separate eventhub_name means the string must not carry an EntityPath, so a namespace-level rule is right and a hub-level one would conflict.

Step 2: A required argument reported missing on a line that contains it

az eventhubs namespace authorization-rule keys list -g "$RG" \
  --namespace-name nautilus-namespace -n RootManageSharedAccessKey
Enter fullscreen mode Exit fullscreen mode
ERROR: the following arguments are required: --name/--authorization-rule-name
Enter fullscreen mode Exit fullscreen mode

In this command group -n is short for --namespace-name, not --name. So I set the namespace twice, the second time to the rule's name, and left the rule unset. The error is accurate and reads as nonsense.

The short alias binds to the command group's noun, not the leaf command's. Use long flags once an az command gets more than two levels deep, because the deeper it goes the more likely -n means an ancestor.

Step 3: The failure I actually want to write down

That failed fetch cascaded through four steps, each reporting success:

CONN=""                              # the failed command assigned nothing
CONN_B64=""                          # base64 of empty is empty, and valid
base64.b64decode("")  -> b""         # valid base64, no error
s.replace(placeholder, "")           # SUCCEEDS, and deletes the placeholder
Enter fullscreen mode Exit fullscreen mode
placeholder_removed: True
endpoint_present: False
Enter fullscreen mode Exit fullscreen mode

str.replace with an empty replacement is a legitimate operation. Nothing threw. The patch truthfully reported the placeholder removed, and left the file holding connection_str = "".

Two things make this worse than an ordinary unset-variable bug. It produced a successful destructive write rather than an error. And the write removed the marker the patch depended on, so a naive retry would find nothing to replace and report success a second time.

Empty-string propagation through base64 is particularly quiet, because base64 has no concept of too short. Every stage of that pipeline is total.

Step 4: The check was in the output and I ran the next command anyway

endpoint_present: False was printed immediately above three failed runs. The check worked. It just was not load-bearing, because both blocks went out in the same message and the second did not depend on the first.

Printing a diagnostic and gating on it are different things, and only one of them stops a bad run.

The replacement gate checks content rather than presence:

case "$CONN" in
  Endpoint=sb://nautilus-namespace*) echo "GATE PASS" ;;
  *) echo "GATE FAIL: do not continue" ;;
esac
Enter fullscreen mode Exit fullscreen mode

[ -z "$CONN" ] only catches empty. A truncated or wrong-namespace value passes an emptiness test and fails at the far end, where the error names a parser rather than a credential.

What the docs recommend

Three notes from the Event Hubs documentation, and one of them corrects something I wrote earlier.

I had recorded auto-inflate as available on "Standard and above". It is narrower: "The Auto inflate feature is currently supported only in the standard tier." Premium and Dedicated size capacity in processing units and capacity units rather than throughput units, so the feature does not extend upward at all.

The scale direction I had right, and the exact wording is worth keeping: "Auto inflate doesn't automatically scale down the number of TUs when ingress or egress rates drop below the limits." It is protection against throttling, not cost control.

On partitions I had "immutable on Basic and Standard", which is right, and the docs add the other half: "For an event hub in a premium or dedicated tier, you can increase the partition count after its creation, but you can't decrease them." So it never goes down anywhere. The same page warns that increasing it changes how partition keys map to partitions, so ordering within a key is not preserved across the change. And a detail that makes the four-partition default easy to live with: "It doesn't matter how many partitions are in an event hub when it comes to pricing." The default costs nothing. It only caps how wide the consumer side can ever go.

Step 5: Verifying with arithmetic rather than a glance

{ "metric": "IncomingMessages", "total": 30.0 }
Enter fullscreen mode Exit fullscreen mode

30 is not "greater than zero". It is exactly 3 runs times 10 events. A non-zero count would be satisfied by one successful run and two failures, by retries counted twice, or by leftovers from an earlier attempt. An exact match rules all of that out in one reading.

SuccessfulRequests came back at 37, which is a different unit rather than seven stray messages: it counts AMQP service operations, including connection and link setup once per producer block.

And because Event Hubs emits metrics at the namespace level, a plain total is the sum across every hub in the namespace. Splitting on EntityName is what keeps the destination in evidence instead of assumed:

[ { "entity": "nautilus-hub", "total": 30.0 } ]
Enter fullscreen mode Exit fullscreen mode

What I learned

terraform state list reads the state file and contacts nothing. It proves what Terraform believes, not what the cloud holds, and the second check has to come from the provider's own API.

terraform plan without -out re-plans at apply time, as its own output warns. In a pipeline, save the plan and apply the file.

enable_dns_hostnames defaults to false on a VPC you create, which is not how the default VPC behaves.

A VPC has no name field, so the tag is the handle every verification uses.

In a nested az command group, -n binds to the group's noun.

An empty variable can produce a destructive operation that reports success, and base64 will carry an empty string through the whole pipeline without complaining once.

Printing a check is not gating on it. Gate on content, not on emptiness.

Compute the number you expect before you read the metric.

So here is the Day 94 question. Which of your verification commands actually leave the machine they run on? I had two checks on that VPC and only one of them was asking anybody anything.

Day 94 down. Six to go.

Top comments (3)

Collapse
 
csm18 profile image
csm •

For your consistency 🙌🙌

Collapse
 
honeykiran profile image
Honey Kiran •

"A command succeeded, so what did it actually prove?" is the exact question, and both halves of your day are the same answer: it proved the step ran. Nothing more.

Terraform's state listing proves what Terraform believes. The Azure step's success proved the script executed — while it deleted the placeholder it was meant to fill. Exit codes report on the command. They say nothing about the world.

The habit that survives contact with this: verify the world, not the report of the world. Read back the resource, the file, the live page — whatever the ground truth is — and grade that. Day 94's lesson is worth more than most tooling chapters: success is a claim, and claims get checked.

Collapse
 
xulingfeng profile image
xulingfeng •

Only six will be 100🎉