DEV Community

Cover image for Day 96: A Private Key in the State File and a 409 That Meant Something Else
Nnamdi Felix Ibe
Nnamdi Felix Ibe

Posted on AI-assisted

Day 96: A Private Key in the State File and a 409 That Meant Something Else

Day 96 of DevOps, Day 46 of Azure. Both tasks ended with a credential somewhere nobody chose to put one. Terraform generated an SSH key and wrote the private half into its state file. The Azure task left two account-wide keys in plain text on a VM, in a shell history, and in an operation log.

The Azure half also corrected a rule I wrote down two weeks ago from a sample of one.

One Terraform task, one Azure task. An EC2 instance with a generated key pair, then an Event Hub backing up to blob storage. The tasks come from the KodeKloud Engineer platform.

Task 1: An EC2 instance with a key pair Terraform generates

An RSA key pair named devops-kp, and a t2.micro called devops-ec2 using it.

Step 1: The configuration

resource "tls_private_key" "devops-kp" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "aws_key_pair" "devops-kp" {
  key_name   = var.key_name
  public_key = tls_private_key.devops-kp.public_key_openssh
}

resource "aws_instance" "devops-ec2" {
  ami           = "ami-0c101f26f147fa7fd"
  instance_type = "t2.micro"
  key_name      = aws_key_pair.devops-kp.key_name
  tags = { Name = "devops-ec2" }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Apply

tls_private_key.devops-kp: Creation complete after 2s
aws_key_pair.devops-kp:    Creation complete after 0s [id=devops-kp]
aws_instance.devops-ec2:   Creation complete after 10s [id=i-ed558886f60d1c409]
Enter fullscreen mode Exit fullscreen mode

That order is not specified anywhere. aws_key_pair references the key's public_key_openssh, and aws_instance references the key pair's key_name, and those two references are the entire dependency graph. Terraform built it, sorted it and executed in order, with no depends_on.

That is the thing Terraform does that a sequence of CLI commands cannot. The ordering is derived from the data, and it stays correct when the configuration changes.

Step 3: Noticing where the private key went

The provider documentation says it in one sentence:

The private key generated by this resource will be stored unencrypted in your Terraform state file.

The plan shows three attributes marked (sensitive value): private_key_openssh, private_key_pem and private_key_pem_pkcs8.

(sensitive value) means Terraform will not print it to the terminal. It does not mean Terraform will not store it. All three encodings of the same private key go into terraform.tfstate in clear text, and terraform show -json hands them back.

Which stacks up into three practical things. The state file is a credential and needs the handling an SSH private key needs, and a local terraform.tfstate in a working directory does not get it. A state file committed to git publishes the key, and git does not forget. And anyone who can run terraform show -json can read the key, which may be a wider set of people than those who should be able to log into the instance.

Step 4: The part that makes it incomplete

Nothing ever writes the key out.

tls_private_key generates the pair. aws_key_pair uploads the public half. The instance launches with the public half in its authorized_keys. There is no output, no local_file, no secrets-manager resource anywhere in the configuration.

So the instance exists, has a key pair, and cannot be logged into. The only copy of the private key is inside the state file, and getting it out means deliberately extracting a secret from state, which is not a thing to build a workflow on.

What the docs recommend

The honest ways to finish it, in increasing order of how much I would trust them.

An output makes the retrieval explicit, and is still a secret in state being printed on request:

output "private_key_pem" {
  value     = tls_private_key.devops-kp.private_key_pem
  sensitive = true
}
Enter fullscreen mode Exit fullscreen mode

Writing it to a secrets manager gets the key into a system built to hold it, and still leaves a copy in state.

The version with no secret in state at all does not generate the key in Terraform:

resource "aws_key_pair" "devops-kp" {
  key_name   = var.key_name
  public_key = file("~/.ssh/devops-kp.pub")
}
Enter fullscreen mode Exit fullscreen mode

Terraform never sees a private key, so it cannot store one. That is the shape to reach for whenever a resource would otherwise generate a secret for you.

Two smaller notes from the same page. rsa_bits defaults to 2048, so 4096 is a deliberate upgrade rather than a default. And ecdsa_curve = "P224" shows up in the plan despite algorithm = "RSA", because it is the documented default for an attribute this configuration never uses.

One correction to my own notes

The main.tf I wrote down does not parse. I had recorded the tags block as tag:{ with Name= "devops-ec2" inside it. The argument is tags, not tag, and an HCL block body needs identifier = expression, so a bare tag: followed by a brace is a syntax error.

The plan output in the same notes shows tags = { "Name" = "devops-ec2" }, and a successful plan and apply prove the file that actually ran had tags = {. So my listing is not the file that was applied.

A transcript of a file and the file are different artefacts, and when they disagree the tool's output is the one that was there.

And one thing yesterday argued against

The AMI is hardcoded. Yesterday I spent real effort resolving a Kubernetes version from the API rather than hardcoding one, because the newest version was the wrong version. An AMI ID has the same problem in a different direction: it is region-specific, so this configuration cannot be applied in another region at all, and it ages out as the image is replaced. The Terraform form of the same fix is a data source, with the same caveat that most_recent = true is the "latest" pattern that failed me on AKS.

The task supplied the AMI, so hardcoding it is correct here. Knowing why it would not survive contact with a second region is the part worth keeping.


Task 2: Event Hub to blob storage, and a 409 I had already explained wrongly

Step 1: The verification that did not fit my own table

anon blob read:      200
anon container list: 409
Enter fullscreen mode Exit fullscreen mode

Two weeks earlier I had built a table saying 409 means PublicAccessNotPermitted, which happens when allowBlobPublicAccess is false on the account. This account's switch was true, and the 200 on the blob proved anonymous access worked.

So I read the body instead of inferring from the status:

<Error>
  <Code>FeatureVersionMismatch</Code>
  <Message>The type of a blob in the container is unrecognized by this version.</Message>
</Error>
Enter fullscreen mode Exit fullscreen mode

Nothing to do with public access at all. The blob type is the problem.

Step 2: Why, which turns out to be documented outright

I had expected to have to reason this one out from the error message. It is stated plainly in the List Blobs reference:

For versions from 2009-09-19 and later, but prior to version 2015-02-21, you can't call List Blobs on a container that includes append blobs. The service returns status code 409 (Conflict) if the result of the listing contains an append blob.

And the version an unversioned anonymous request runs under is documented too:

If an anonymous request to a general-purpose storage account doesn't specify the x-ms-version header ... the service uses the earliest possible version to process the request. If the container was made public using the Set Container ACL operation using version 2009-09-19 or later, the request is processed by using version 2009-09-19.

The two halves meet exactly. My request ran as 2009-09-19, the container held an append blob, and the service is documented to return 409 for precisely that. One header fixes it:

curl -H "x-ms-version: 2021-08-06" "${BLOBEP}${CONTAINER}?restype=container&comp=list"
Enter fullscreen mode Exit fullscreen mode

One refinement on what I wrote earlier. I said anonymous requests are served by "the oldest service version, 2009-09-19". The documented rule is "the earliest possible version", and the floor depends on the account kind: 2009-09-19 for a general-purpose account, 2014-02-14 for a Blob Storage account. Both are before 2015-02-21, so the same 409 happens either way. The finding is more general than I claimed, not less.

Step 3: Correcting the table rather than extending it

Status Code Cause
404 BlobNotFound or silent Container private, account permits public containers
409 PublicAccessNotPermitted allowBlobPublicAccess: false on the account
409 FeatureVersionMismatch Anonymous request on an old default version meets a newer feature
200 Public access working

Two unrelated faults share one status code. My Day 38 note said the status code tells you which layer blocked the request. That was an over-generalisation built from a sample of one.

The error code tells you which layer. The status code narrows it to a class.

The blob read succeeded on the old version because fetching bytes does not require the service to describe the blob's type. Only the listing has to serialise <BlobType>.

And the blob type came from the task's own script: upload_blob(log_data, blob_type="AppendBlob", overwrite=True). Had it used the default BlockBlob, the unversioned listing would have returned 200 and I would never have found any of this. Which is a decent argument for testing the behaviour you promise rather than the configuration you set.

What the docs recommend

Three habits from this one, two of them fixing yesterday's mistakes.

Count before writing. Day 44's patch destroyed the placeholder it was looking for. This one counts first, and a half-patched file is not a reachable state:

if n1 != 1 or n2 != 1:
    print('ABORT: unexpected placeholder count, nothing written'); sys.exit(1)
Enter fullscreen mode Exit fullscreen mode

Hash both sides of a transfer. The task's wording is "copy the script from the client host", so the copy is a graded step, and 100% 964 8.1KB/s is a progress bar rather than a check. Two md5sum calls make the requirement verified instead of attempted.

And compute the expected metric before reading it. The first metric read showed 2 messages after three successful runs, which invites a wrong conclusion in either direction. The arithmetic settled it: 92 bytes over 2 and 138 over 3 both give 46 bytes per message, so the two readings were the same data at different completeness. A check for non-zero would have passed on the first reading and told me nothing.

What I learned

tls_private_key stores the private key unencrypted in state, in every encoding it produces. (sensitive value) in a plan means not printed, not not stored.

Generating a key in Terraform and never outputting it produces an instance nobody can log into. Prefer giving Terraform only the public half.

Terraform derives execution order from resource references, so a three-resource chain needs no depends_on.

When a transcript of a file and the tool's output disagree, the tool's output is the file that ran.

One HTTP status can have unrelated causes. Read the error code, not just the status.

Anonymous Azure Storage requests run under the earliest possible version, which is from 2009 or 2014 depending on the account kind, and List Blobs on a container holding an append blob returns 409 on anything before 2015-02-21.

Count what you are about to replace and abort before writing.

So here is the Day 96 question. Where is the private half of the key that gets into your servers? Mine was in a JSON file in a working directory, in plain text, and I had not put it there on purpose.

Day 96 down. Four to go.

Top comments (0)