8 ms·
I made a mistake with Terraform and Azure made it worse
- Arnavion 5y agoWell, Azure prevented you from creating a RG but still let you delete it because that was the role that the client configured for you. AFAIK there's no built-in role that behaves like this, but it's probably a very easy mistake to make - grant permissions on resourcegroups/$name/* , forgetting that * includes delete. re: SQL Server backups, I assume this was VMs running SQL Server rather than Azure SQL DB (the managed one) ? If it's the latter, then I think the backups will be retained even if the RG is deleted.
- zug_zug 5y agoWhere I last worked, all terraform changes went through PR, requiring approval, after having read the plan. It was using a system called atlantis. It was slow, but it prevented issues like this.
- Pokepokalypse 5y agoThis is the way. (we use gitlab-ci's built-in review process for approval). At the end of the day, approval's still a human job, and humans make mistakes. Right? :D Terraform is an incredibly powerful tool, and you can make some monumentally huge mistakes with it.
- carrja99 5y agoAtlantis is great. If you've grown beyond 5 or so engineers you should have no excuse to be running terraform apply from laptops.
- throwaway290232 5y agoIt is completely embarrassing how many engineers we have and still apply manually from laptops. Changes are slow and error-prone, we don't even have them hooked up to CI/CD. I think it still works because we have so many damn engineers and we don't actually need to change infrastructure multiple times a day. That said, Terraform breaks so often that if we did it all automated, we'd have a million more Git commits from trying to fix broken apply's.
- arlk 5y agoSame, not atlantis but we used Gitlab-CI and Jenkins steps for an approval whenever there's a change in production, while staging changes are auto-deployed. Terraform plan was written to the PRs using tfnotify[0]. Normal deployments typically took 1 minute and 20 seconds (for each environment, in parallel) which I would consider very reasonable considering that we deployed a medium size infrastructure with only 2 terraform layers, so there was a room for optimizations. [0]: https://github.com/mercari/tfnotify https://github.com/mercari/tfnotify
- yashap 5y agoAtlantis was actually created at my previous workplace by a couple of my ex-coworkers! Agreed that it’s a great way to bring a bit more care/rigour to always-dangerous infrastructure changes. IIRC we had it configured so that you had to always had to do things in this order: - plan against staging - get a PR approval - apply against staging - plan against prod - apply against prod - merge Being forced to plan (and get someone up review said plan) before applying makes it far, far less likely you’ll do the level of damage described in this blog post.
- arlk 5y agoFrom what I experienced, per-environment branches is a bad practice that eventually will be a big burden to deal with especially when environments don't match. Actually the concept of "staging" in infrastructure is different than it in code, which is the usual source of confusion. The best strategy is to have a repository for your modules only so you can specify the version[0] you want to use, and separate environments by folders. [0]: https://www.terraform.io/docs/language/modules/sources.html#modules-in-package-sub-directories https://www.terraform.io/docs/language/modules/sources.html#...
- yashap 5y agoYeah, we just had a single feature branch, which we would merge into the single master branch. We’d simply apply it to staging first, make sure nothing terrible happened, then apply to master. All those steps I listed above happened on the same branch, same PR.
- bwship 5y agoWe had the same issue with DynamoDB, that Terraform is all to happy to delete a table it deems acceptable to delete. Which in 99 out of 100 cases is never the case. It is a very aggressive IaC tool.
- notwedtm 5y agoIt's a very powerful tool. Just like any other (well designed) tool, it's only going to do what the operator tells it to do. Terraform will never delete something you don't tell it to.
- anonydsfsfs 5y ago> Terraform will never delete something you don't tell it to. Not necessarily. With some providers (e.g. Azure), Terraform will fail to recognize automated behind-the-scenes changes and try to revert them, causing serious breakage. This is why the "ignore_changes" meta-argument exists. See https://itnext.io/how-and-when-to-ignore-lifecycle-changes-in-terraform-ed5bfb46e7ae https://itnext.io/how-and-when-to-ignore-lifecycle-changes-i...
- throwaway290232 5y agoAlso why the create_before_destroy argument exists. Often you have to apply one or the other to a resource, or it simply falls into an infinite loop of creating and deleting the same resource.
- throwaway290232 5y agoActually that's impossible to know. Terraform doesn't delete anything at all. It asks provider plugins to remove a logical concept/placeholder, and the provider issues API calls (based on various criteria, some of which is not known until apply time, even with a plan run) and those API servers then do various things in the background based on criteria Terraform doesn't know about. Sometimes you need it to delete something, and it won't. And sometimes something else in the background gets removed by the provider or API service handling the first delete. Terraform is "powerful" in the sense that a 6'11 230lbs 30 year old blind man with an IQ of 85 is "powerful". And it's definitely not well designed, or there wouldn't be multiple large projects dedicated to fixing its many problems and missing features (terragrunt, terraformer, etc)
- comice 5y ago"immediately raise a ticket with Azure Support, who were able to grab the resources from “somewhere” (I guess when you delete a resource in Azure, it’s still on a disk somewhere, for a while), and we got our database and backups back" what the hell is Azure doing pretending to delete things? How long do Azure keep your data after you think you've deleted it? Is there a way to ensure data stored in Azure is actually destroyed when you ask for it to be destroyed?
- macintux 5y agoI can't speak to any specifics, but asynchronous behavior, including deletions, is very common in large distributed systems, and Azure I'd wager is no exception. Update: I'd forgotten that even filesystems often do a soft delete. https://lwn.net/Articles/462437/ https://lwn.net/Articles/462437/
- NicoJuicy 5y agoIt is destroyed. But i believe there is a timeline where azure support can recover it for you until the deletion is final.
- Arnavion 5y agoA bunch of high-profile resources have temporary soft-deletes - resource groups, managed SQL DBs, KeyVaults, Storage Accounts, and even subscriptions themselves. For some of these the undelete option is given to the user, for others you have to call support.
- carrja99 5y agoThere's a song in Hamilton that I'm always reminded of when terraform applies run: "Blow Us All Away"
- aequitas 5y agoYou can (and always should) decouple the plan and apply steps. For a non terminal approach this can be done by outputting the binary plan to a plan file (with -out=path) and reviewing the plan terminal output which will show all actions Terraform will perform in human readable format. Then have the plan file be used as input for the apply step. The apply won't perform any other action that was not in the plan file (which matches the output that was reviewed) and if state of the environment it would apply to has changed in the meantime it will abort without causing undesired changes and you can restart the process again. There is also the prevent_destroy[0] meta argument for resources but afaik it has no effect when you remove the resource from your .tf files[1], so it would not have helped in this case. [0] https://www.terraform.io/docs/language/meta-arguments/lifecycle.html#prevent_destroy https://www.terraform.io/docs/language/meta-arguments/lifecy... [1] https://github.com/hashicorp/terraform/issues/17599 https://github.com/hashicorp/terraform/issues/17599
- operatorius 5y agoThis! In addition to that things can be made even less error prone. Ive done this using yaml pipeline in azure devops. The plan task can be used to set an output variable which indicates if the generated plan contains any changes. That boolean value is used as a condition to trigger a manual verification task which basically prevents apply running if there are any changes without reviewing it first. As the op mentions, the generated plan is an artifact itself that is used in a following apply task
- thedougd 5y agoI'm not very familiar with Azure anymore, but AWS also offers deletion protection on RDS and other services. This forces a two-phase operation with Terraform. You must first apply configuration to remove the deletion protection, then in the second phase you may delete the RDS instance. Unfortunately, I've never been able to get much mileage from the Terraform prevent_destroy lifecycle option because it can't be set from a variable. Most of my configurations use a module and pass different variable values per each environment. I'd want the lifecycle flag in production, but maybe not dev.
- 5y ago
- Androider 5y agoIn my opinion, databases are not cattle, and don't need to be automatically created (and destroyed!) in your main Terraform plan. It's perfectly OK to have a completely separate Terraform project that just configures the DB initially (or even manually, I see lots of places running DB's that predate Terraform with immutable infrastructure for everything else), and applies minor non-destructive changes in the future. This way you get the benefits of IaC, but the DB plan doesn't participate with the rest of your infrastructure that IS ok to blow away and re-create at will. BTW, Amazon RDS backups work the exact same way: Destroy the database and the backups are also destroyed. Therefore, same region automated RDS backups are fine for day-to-day, but in a true "DB goes poof" disaster you should expect that you WILL lose them too! You need cross-region, or even better, cross-account DB replication or snapshots to survive this.
- k__ 5y agoI don't know much about Terraform, but at least in Pulumi you can mark resources as protected to prevent accidentally deleting them.
- disordinary 5y agoYou can do it both in Terraform and also at the resource level in Azure itself.
- jiggawatts 5y agoThat's chock full of bugs unfortunately. For example, if you lock an Azure DNS Zone to prevent it being deleted, you then cannot delete any DNS record under it! It's a strict hierarchy, there's no way to turn off the inheritance. (It is possible to create a custom RBAC role that excludes zone deletion only, but this is very fiddly and not-quite-the-same in complex ways.)
- digianarchist 5y agohttps://learn.hashicorp.com/tutorials/terraform/resource-lifecycle?in=terraform/state#prevent-resource-deletion https://learn.hashicorp.com/tutorials/terraform/resource-lif...
- camjohnson26 5y agoDoesn’t terraform show you how many resources are affected and require you to approve that when running apply?
- knownjorbist 5y agoIt does, but according to the post it was run via Azure DevOps. I'm not familiar with ADO but it sounds like it might not have been as obvious as running locally. Alternatively, perhaps it would have only shown deleting the Resource Group, but internally to Azure(and unbeknownst to Terraform) this means deleting everything within the RG as well.
- rjbwork 5y agoWe run our Terraform pipeline via Azure DevOps. We separate the plan/apply steps, stash both the binary and json version of the plan, stash the logs of the plan, and require increasing levels of approval as it moves through each environment on it's way from dev to prod. To go to prod it needs 4 people to have reviewed the plan - the person whose PR triggered the release, a director, a team lead, and another engineer. This is enforced using Azure DevOps' baked in pipelines and approval functionalities. To keep from nuking things we completely disable destructive operations from our AWS/Azure Terraform user and in fact, limit what the user can do as much as possible, only giving it the permissions needed to create what we use, and adding as necessary. For deletes we add a very targeted permission that we revoke after deployment. It can seem onerous at times, but ultimately it's a far smoother process than legacy manual or scripted deployments and is very repeatable and visible. It's also a good thing to have lots of eyes on critical infrastructure changes anyway.
- caymanjim 5y agoIt sounds like the fundamental problem here is that the account credentials for environments are shared. You shouldn't have permission from one environment to modify the assets of another. Every environment should have its own segregated account ID. Then you can't import the wrong resources. The state files should be segregated as well, so that when you're running Terraform on Account A, it can't even see the state file for Account B, much less mix them up or compare them to the wrong environment. It sounds like the user running Terraform had access rights to multiple environments. This sort of thing was inevitable.
- corty 5y agoOne of the big mistakes I see here is that the testing environment A doesn't look and work the same as the prod environment B. The closer both are, the surer you can be that you can catch such mistakes by testing in A. The bigger the differences, the more problems can sneak in undetected. So while I think it is OK for the author to be a little humbled by his mistake, I would actually place the blame on the misdesigned environments. We should try to expect human mistakes and make them avoidable (by noticing them early in the test environment) or prevent them alltogether (by automatically testing and only allowing the change to production, but that is far harder to setup).
- cameronh90 5y ago"One of the big mistakes I see here is that the testing environment A doesn't look and work the same as the prod environment B" This is a nice aspirational goal, one that you should definitely aim for, but I have never seen a situation in a non-trivial app where the test and prod environment are even close to identical. All large apps I've worked on end up with external dependencies that themselves don't have a test system and have real world side effects (like buying things), so straight off the bat, all of them need to be mocked out. Then there's no way we'd get budget for a 1000+ node cluster on our test system, so naturally there are entire classes of high load / large network bugs that are less likely to crop up. Finally the test systems are often not allowed to handle prod data for regulatory reasons. Thus, everything needs to be either synthetically generated or stripped versions of prod data, which unsurprisingly sometimes behaves rather differently. Even if you think your test environment is a pretty good replica of prod, chances are it's probably not as good as you think. So you should always have processes in place to be able to slowly rollout deployments and halt/rollback if there are issues. Everything should always be backed up. And importantly, this should not all be controlled by a single deploy script with global permissions - anything that deletes backups should need explicit multi-step approval.
- habeebtc 5y agoIndeed. Duplicating Test and Prod can be tens of thousands of dollars (or more) a month. You have to invest big time in automation to build up and tear down any decent sized environment to save the spend there, and that itself costs money.
- pplanel 5y agoyou should have a look at terraform workspace feature.
- orangejewce 5y agoworkspaces are specifically _not_ intended to be used as environment replacements. And it wouldn't have caught the OPs issue to begin with. His problem was he didn't read the plan, because it's pretty basic that any change of a resource name or a change of type equates deletion and TF will report back saying it will destroy a resource that is missing in the config but in the state. To solve his problem, after switching to the data source type from resource he needed to manually run `terraform state rm` to get rid of the resource from the state.
- charsi 5y agoCan you elaborate on why terraform workspaces are not intended to be used for environments? I use it exactly for this use case. Same terraform config deploying to production and staging, each maintaining its own state in a separate workspace.
- aurantia 5y ago> workspaces are specifically _not_ intended to be used as environment replacements. From Terraform's "An Overview of Our Recommended Workflow"[1]: "The best approach is to use one workspace for each environment of a given infrastructure component. Or in other words, Terraform configurations * environments = workspaces." So 1 workspace != 1 environment but workspaces are indeed intended to handle multiple environments. I've personally struggled with managing multiple environments using Terraform so I'm interested in what the best practices are. [1]: https://www.terraform.io/docs/cloud/guides/recommended-practices/part1.html#one-workspace-per-environment-per-terraform-configuration https://www.terraform.io/docs/cloud/guides/recommended-pract...
- arecurrence 5y agoI keep databases and other single data source constructs out of terraform. Sure, there are mechanisms to prevent deletion but all it takes is one bug (and terraform has many) for all your backups to tear down. I also infrequently backup single sources off cloud to prevent ransomware payoffs. It has the secondary feature of providing a recovery source if things go off a cliff in the production environment.
- vimwizard 5y ago>I keep databases and other single data source constructs out of terraform Glad I'm not the only one that saw this as the right choice.
- jrockway 5y agoCouple things: 1) It is so weird to me that every cloud provider deletes backups when you delete the SQL instance. We take offsite backups that are decoupled from this process. Fortunately someone made a shell script to do this that has worked quite well: https://github.com/ovotech/cloud_sql_backup https://github.com/ovotech/cloud_sql_backup (you can then just copy the Cloud Storage buckets to S3, so when you Google account gets banned you still have your database). 2) I hate to be "that guy", but I'm starting to wonder about gitops. I really, really like having all infrastructure changes recorded in machine-readable format with history. Pry it out of my cold, dead hands. But you also lose a ton of important tools, like the diff and the sanity check before you deploy. You could have a CI rule that does the diffs, but then CI has to touch production which is not ideal. You could have CI do a dry run of HEAD and a dry run against your PR, and diff those two, but honestly no CI systems really let you check out multiple branches and use them as an input to the script, so have fun hacking that up. You end up with workarounds for workarounds and the net result is that your auditable infrastructure comes at the cost of taking a human out of the loop (and slows down experimentation). I don't think the model is quite right quite yet.
- easton 5y agoIsn't the answer to 2 to have a pre-production environment to calculate the diffs/changesets/etc against, or even to deploy the change to to test it? I know with CloudFormation, for all its faults, is pretty good at making a hypothetical changeset before it runs, and if that's not safe enough, you can just deploy it to your dev environment and use the changes succeeding and your service being up as a integration test.
- whimsicalism 5y agoI don't understand the problem. Use something like `terraform plan` as a comment on the pull request and manually look over the changes before pulling in.
- spondyl 5y agoI don't use Terraform but I think you're describing something like Atlantis? https://www.runatlantis.io/ https://www.runatlantis.io/ I remember seeing a team running this at a previous company I worked at
- decker 5y agoAfter working with declarative systems for some time now (terraform, kubernetes), I've concluded that things will generally be declarative, but you're bound to run into edge cases where the imperative nature of the underlying system bleeds through and shows up as a gotcha for some reason or other. For kubernetes, I've found that people tend to have to name YAML files in the order in which they should be applied for things to work properly. A more devious case involves kubernetes ConfigMaps getting updated in place via apply while the deployment fails to recognize that the environment variables for the pod have now changed and need to be restated. I suppose this could be chalked up to the idea that all declarative systems need to be functional and each resource should be immutable, however, that's never how it evolves in practice. In short, it's all been quite a disillusioning journey through the general promise of not needing to worry about ordering that eventually results in ordering being the hardest problem that the system faces.
- reilly3000 5y agoI'm not sure about Terraform, but Pulumi has an options object that can set parameters about how Pulumi interacts with that resource. I tend to enable `protect` on database resources which prevents Pulumi from deleting it. AWS has done a great job at making it difficult-to-impossible to tear everything down in a single command. There are rate limits on resource deletion and no single place to remove items in bulk if not managed by Cloud Formation. I spent the better part of a couple days trying to clean up an account from all of the random supporting services that get created over the years. If I'm wrong about this, please let me know!
- smorephism 5y agoTerraform supports this by setting prevent_destroy = true in a resource's lifecycle, which I discovered after I accidentally vanished an entire Elasticsearch domain—fortunately, though, not prod.
- herpderperator 5y ago> but the sheer magnitude of carnage resulting from a one word change in terraform was surprising You are giving a relatively new tool full access to your datacenter. Here be dragons. This mistake is obviously something that would never happen when using the official UI, at least not without descriptive explanations and warnings in the process.
- thedeusx 5y agoY'know, normally I'd be relatively forgiving as none of us are perfect, but jeesus this is a clusterf** of an article. The author, a "Director of Consulting" might want to do some training (Both Hashicorp and Microsoft have free training). Why in the hell would you have the same statefile for different environments? Why would you have these environments in the same Azure subscription? Why would you run your terraform so infrequently that you'd forget about a botched statefile move? Why would you not read TERRAFORM PLAN (It's LITERALLY WHAT TERRAFORM DOES)? I also suspect that while the author's probably heard of a CI/CD pipeline, they're running their IaC from their local machine, given the tone of the article. Why, for a production database that contains information not contained elsewhere, would you not configure an Azure Recovery Services Vault? Like I get it, people make mistakes. I once did something similar with an overenthusiastic use of terraform destroy, but this guy just seems like an absolute cowboy who doesn't really know what he's doing.
- benjaminwootton 5y agoThe problem with Terraform and IAC is that there’s a big gap between learning how to use it and then learning how to use it in a safe, scalable way. It’s the same with something like a programming language where there are thousands of best practices and foot guns, but infrastructure as code is more dangerous and much newer. There are also less books, venues and even training courses to learn these practices. There are also a vanishingly small set of engineers who have actually done this in production at scale so it can be hard to find experienced people.
- thedeusx 5y agoI've worked with at least several hundred of them over the past 5-10 years. Granted, I'm in Europe and the author is in the US, perhaps you are too. I'm not sure what talent/skills are like there. In several firms I've worked in now someone missing so many things wouldn't be above consultant level, and wouldn't be approving PRs let alone deleting a live prod off from their local laptop without some significant questions being asked. I get everyone must learn things, but when you position yourself as a technical expert (Director, in this case) you should have enough experience to be a bit more thorough with your work so if a mistake happens, there's a way out, or just not make what amounts to several design and implementation mistakes. Part of what I think makes this a little egregious is the author didn't f** up his own systems, he f**'d his clients. I'd understand a little more if it were "I'm the in-house guy upskilling" rather than "look at this mistake I made as a (presumably) highly paid outside consultant literally brought in to make sure stuff like this doesn't happen". However, I still must give absolute kudos for sharing mistakes publicly. We all do make mistakes, and most people try and hide it. When the author realised there was an issue, every step after that was handled like a pro.
- havkom 5y agoAzure’s support is great! I am not surprised they quickly helped out. First time I contacted them I was not hoping for much. But after a few contacts I realize they must be one of the best support orgs in the world. They can quickly help out with anything from very trivial questions to helping out with very difficult faults, and do this without having to be harassed about escalating my tickets. Outstanding.
- bavell 5y agoI've had the exact opposite experience trying to get support setting up a VPN to connect an on-prem server with remote clients (using self-signed certs and terraform). I'm not very familiar with Azure and I was volunteering my time/expertise but the support (paid but basic plan, I think $100/mo) was very underwhelming. The support technicians were all Indian and while they were polite and had good English, the time difference made the back-and-forth painful. Spent over a month trying to resolve the issue but I must've been talking with tier 1 support because it was obvious the support technician wasn't very technical (asking very basic questions that I had already answered, couldn't answer any of my questions without getting back to me days later). Combined with the quirks and performance issues (30+ mins to setup VPN gateway) it was a very poor experience and I wouldn't choose to work with Azure in the future.
- rcarmo 5y agoBlaming Azure here feels quite disingenuous when there are so many layers of breakage in the approach (manual apply, TF state across subs, a hack to remap a resource, assumptions about how databases are handles, etc.)
- raziel2p 5y agoNot entirely related but I'd also recommend thinking hard about your resource groups in case you ever need to move or re-create them. Due to the way azure and terraform works, it's "safe" to put all your stateless resources in one resource group, but everything stateful should be in individual, small resource groups. This will be a life saver if you ever want or need to move your stack across regions using azure's built-in georeplication rather than restoring from slow off-site backups.
- qxmat 5y agoThis wouldn't have happened with a separate state file. Additionally, as said below, plan + apply must be separated with a ManualValidation task to allow release administrators to manually inspect the plan output on a production deployment. Terraform's "-detailed-exitcode" will help you tailor the pipeline if there's nothing to do (0 - plan success, no changes, 1 - error, 2 - plan success, changes). I'm also of the opinion that prod/non-prod subscription and resource groups pairs should be "vended" to you by another department (i.e. you're a user not an owner). This prevents you accidentally destroying the entire hierarchy.
- shog_hn 5y agoI mostly work with AWS, but have used Azure in the past and remember the Resource Group concept. It is quite dangerous when coupled with Terraform (or any IaC tooling for that matter). AWS RDS has a feature where if you delete a DB instance it prompts you to take a final snapshot of the data. I haven't used Terraform in just over a year now (have been using aws-cdk), but as far as I remember, Terraform deletes of RDS instances would require you to add a 'force' argument/option to override the prompt for the final snapshot. Something like this seems like a no-brainer for Azure SQL when deleting instances. Also, with TF its always best to plan, write the plan output to a file, and then run apply against that plan (after having studied it!)
- AtNightWeCode 5y agoFirst, I recommend to have different subscriptions for each environment. Second, the thing that is really nice with Terraform is that you can see what it plans to do before it does it. One can also set it up in the CI/CD pipelines to align it with other change processes.
- dekhn 5y agoall I can say after using all the various systems is that borg /google3 is still the best resource manager I have ever used. It's not impossible to prevent mistakes but there are a number of very powerful things due to the monorepo and deploy-at-HEAD approach that make it possible for many teams to provision resources within a limited number of accounts.
- franzwong 5y ago> I will cut corners and do a terraform plan on just one of these environments and then terraform apply on all of the others. We don't do this because preproduction is being used by the business actively. It is treated like production environment. But it depends on companies.