Strategy for CI/CD when your infrastructure/CFN templates lives with your code

I’ve had trouble wrapping my head around how CI/CD should work for cloud apps where infrastructure lives with the code and I haven’t found a great refarch or best practices guide.

First, there is the deployment pipeline, itself. Some CI/CD providers have rigid stages (I believe codepipeline has rigid stages in that they can’t be created at code build time; correct me if I’m wrong!) in contrast with some other providers that create the stages at build time accorsing to a yml file. So, where to put the Codepipeline is issue number 1. Do you manually put your codepipeline into your production account or do you keep it outside and deploy into production

Then, issue #2 is what order does everything happen. Do you create a change set for the infrastructure, build the code, deploy the infrastructure, deploy the code? Separate pipelines?

What if you have an AMI that depends on a docker image that needs to be built? Seems like things get messy quickly, curious how everybody takes this challenge on


Related discussions:

I use a different CI (Buildkite) that allows me to define the steps in the deployment so infrastructure deploys first then code. Other CIs like Circle/Jenkins follow this structure too.

For me personally ci-cd is not on the whole code (infra code and app code together) but on every piece of the code.

infra code has:

  • CI => create an artifact (publish it somewhere) that goes through all your enviroments (this can just be a copy of yaml/tf files) in our case it is a python script that generates x amount of yaml files)
  • CD => Deployment of the created artifact (together with a custom properties file) on those environments

App code has the same:

  • CI => Create docker image, war, jar, … publish it
  • CD => Deploy that artifact

Then it comes down on dependencies: Apps you will want to deploy without any changes to infra. so you this could be a separate pipeline

When you deploy infra, you will want to deploy a new version of the app as wel, so you could create a step in your pipeline that kicks off the app pipeline when infra is complete

If everything lives under one repo you then it is also possible with one pipeline with both infra and code and just go through the actions (build app, build infra, deploy infra, deploy app), but in larger projects (with specialized devs/ops guys) this tends to cause some issues

I personally think the decision to store infrastructure templates within the code base is somewhat specific to the type of infrastructure and, indeed, type of code you intend to be running.

In the case of, say, Serverless, where you’re defining some API Gateway config, Lambda functions, maybe an S3 bucket or a DynamoDB table, it simply makes sense for the infrastructure and application code to reside in the same repository. If anything, Serverless (and certain other frameworks, I’m sure) reinforce the idea of storing your application code alongside your infrastructure code.

So why is that okay? I guess because in a Serverless project, application code and infrastructure code are tightly coupled; in a sense, you can’t really have one without the other - both tend to be developed somewhat simultaneously. One might think of these “serverless” resources as being modules or libraries required by your code in order for it to run, in which case it makes sense to have them within the same codebase because direct modification of the infrastructure resources themselves can directly lead to an impact on the ability for the application code to run successfully. Most importantly, because application and infrastructure are so tightly coupled by design, both elements may often be modified within the same release or even the same pull request. Simply from the point of keeping some form of version sanity, it makes sense to couple your infrastructure and application code in this scenario.

On the other hand, if we’re talking about an infrastructure wherein your application code is running on a more persistent “hosting” solution (docker, ec2 instance, bare metal, smart fridge), the fact that the infrastructure is persistent immediately hints towards it likely requiring far fewer changes relative to the application it is hosting. Does it make sense in this situation to keep infrequently-modified infrastructure code within the same repository as constantly-updating application code? I’d say no. Why? Well, for starters your build process immediately needs to account for the fact that the infrastructure hasn’t changed, unless you want to wait on your framework of choice to check the existing infrastructure state and report back that there are no changes to make because it doesn’t care whether or not the actual template files have changed. For every build. So you need some logic to diff the latest commit’s infrastructure-specific files against the previous commit and conditionally run your infrastructure deployment if it has changed. This already sounds exhausting, and I just said “for starters”. If you’re still not convinced, you now have to dance the delicate dance of ensuring everything is built in the right order such that your Docker image exists by the time it is requested by a container host or whatever you’re doing. Decoupling infrastructure and application code means you can just build the new container/ami/smart fridge rom whenever a change is merged into the main branch.

Personally I handle this by pushing new images with multiple tags - latest, and the commit id. Before I push the new image, I re-tag the existing latest image, removing the latest tag from it. Your infrastructure always grabs from latest; it no longer has to care about your application code build pipeline at all.

So to actually stop ranting and answer you - all the issues you’re listing are exactly why I don’t recommend storing infrastructure and application code together, but this is obviously very contextual, and I gave an example earlier of when you might want to couple infrastructure and application code tightly.

  1. Personally I keep a separate “build” account; it contains all build-related resources and has federated IAM access to assume build-specific roles within my prod/staging/etc. accounts.

  2. If you decouple the infrastructure code from the application code, you don’t need to worry about timing them. With regards to an AMI that depends on a docker image being built, I’d trigger the ami baking process from an ECR:PutImage event. This method is also a form of decoupling - you shouldn’t have to worry about timing things; everything should be event-based wherever possible.

The infrastructure build is triggered by a commit to the main infrastructure branch. The application code image is triggered by a commit to the main code branch. The AMI baking process is triggered by the application code image being pushed to ECR. Rotating the new AMI into your ASG is triggered by the completion of your AMI bake, and so on.

Right now you’re trying to play chess, managing a whole bunch of different pieces that all behave in different ways and need to be closely considered and orchestrated in order to effectively work together. This is no fun. You need to play Dominoes.

Interesting question. I follow the following pattern now:

  • One Gitlab repository for every service (a service to me is something that needs to be independently running with the least amount of dependencies to other services)
  • every repository has a Gitlab file that triggers deloyment for every stage, every stage has 1 AWS account.
  • every repository has a cloudformation.yaml
  • for deploying the cloudformation I use 1 AWS codepipeline per service per account (so that also if I need to do changes within VPC, I have the pipeline inside the VPC - no ugly access from outside the VPC)
  • the boundaries of a service are with http and AWS SNS, stacks cant communicate with each other in another way than those 2 options.

The biggest drawback here is that I have to create and maintain a codepipeline for every service/repo that I introduce. Is that bad? Maybe, but not as bad as the other options I looked at.

Gitlab pipeline has the following flow:

  • Build (creates an artifact and tests it)
  • Deploy to test (passes the artifact to test AWS account S3 bucket)
  • Deploy to production (passes the artifact to production AWS account S3 bucket)

In deployment phase cloudformation (triggered by codepipeline) really takes care about everything that needs to be done to deploy the infrastructure and the code (lambda or containers). Only something like database versioning is taken outside of that.

Rollback is part of Gitlab and usually also involves another update to the cloudformation stack. For this it is handy to use something more blue/green if you need that, as it might take minutes before the rollback is fully applied.

The Gitlab file both gives structure and flexibility. So to get it deployed to all stages it needs to follow a certain pattern. What happens in order to prepare the deploy is all fully in hands of the person that writes the Gitlab file. E.g. sometimes you might want to build a docker image for a service. That is part of that specific service’s Gitlab file.

This was a really great reply. Well explained, thank you.

The core unit of testing and deployment is the “artifact”, which can be anything from a tarball to docker image to helm chart. These should have a pipeline to move it from code to delivery, so you may have an application that depends on infrastructure, those are two independent pipelines, one dependent on another. These are best expressed in some sort of uniform DSL, which is often the case why YAML is used for this.

For CI and CD, these are should be two independent pipelines ideally, otherwise, things get very complex quickly.

The goal in CI should be to hook into the code repository (github) and deliver (push) to an artifact repository (like ECR or other docker registry).

The goal of CD should be to hook into the artifact repository (like ECR) and delivery (deploy) to an environment, such as test, stage, or production (blue, green).

In CD, if you use code (artifact rather) promotion, you can deliver to test env, and after tests, promote the artifact to stage env, and then after more tests, promote to prod env (blue prod env for canary blue/green deploy scenarios).

In CI, if you use trunk based versioning, each merge to master, get versioned and kicks off the start of the pipelines.

Many places use branching (freature branches, hotfix branches) due to deployments that are planned events (such as 1 every 2 weeks). This makes versioning, and naturally deployments more complex, often interleaving CI with CD and resuliting in a complex hard to maintain mess.

Thank you. Follow up, monorepos or multirepos? Client webapps, admin webapps, backend infrastructure.

Follow up, monorepo or multirepo/one-per-service?

You sort of talked about, but I’m following up with people to ask monorepo vs multirepo/one-per-service preference

This event based approach is also a really good idea though it will take a bit more setting up

If you are doing web apps plus APIs I think a monorepo makes a lot of sense. Since we switched I haven’t regretted it.

Infrastructure as code doesn’t mean build infrastructure code as applications. You don’t need to build a restful service that creates infrastructure in order to create infrastructure as code.

Just do a pipeline using a CI/CD framework and inside the pipe you execute your code.

For example use Amazon Deployment Framework to manage your Codepipelines and then ice CDK to write your infrastructure as code.

Several CIs let you filter on branches or paths, so you really could use a single repo if your CI is one of them.

I have a few pipelines where the deployment code is in the same repo as the application code, using this approach. Each pipeline has filters such that changes to the other component do not trigger a build.

don’t think too much ahead, see what works for you. start with something and see what works … We came to our conclusion of a separate pipeline for app and infra because running through the infra phase all the time delayed app deployment. incremental changes :wink:

Okay so when you say “monorepo” and “multirepo”, I assume you mean having a single repo for a “service” versus having various features of that service in their own repos. Basically extending your question regarding infra/app code in the same repo, but, like, for app-specific features?

So let’s say we have a client web app; it also has an admin portal. For the sake of this example we’re hosting it on ECS but whatever - compute resource is compute resource.

Starting out, I immediately go back to my previous comment - I determine how I might logically manage the “meta” of this project based on how the project is being built. I can assume that the admin portal, though technically maybe an entirely separate API and MVC (or whatever), is probably going to be tightly coupled with the client app - this is because, I imagine, changes to one will likely result in changes to the other. In this case, I’d probably keep both the client and admin “apps” in the same repo - I’d probably configure a specific env var that determines whether the app is being hosted in “client” or “admin” mode. You could probably just host both app and client in the same container/instance/whatever, but let’s say for the sake of this example that I’m a considerate engineer who understands that we probably don’t want a situation in future wherein both the client and admin apps go down at the same time. We probably at least want them decoupled from a “hosting” perspective, though not from a code perspective.

When you say “backend” infrastructure, I’m going to assume you mean the application backend - the “controller” code that makes the app actually do the things.

Again, unfortunately, we meet that bitch context, because in this industry there isn’t always a one-size-fits-all answer. Here I’d take “inspiration” from how the development teams work - is there a separate backend and frontend team? Is their versioning decoupled? In most semi-complex applications, you’re probably going to see a bunch of changes to both back-end and front-end that are not directly related to oneanother. Modifying CSS or client-side JS or whatever on the front-end does not require any backend changes. And vice versa. In this case, it makes sense to separate them.

Let me know if I’m misunderstanding your question. I misunderstand a lot of things.

Will this be the same in SAM? The nice thing about the in SAM promoted pattern is that you release your infrastructure and code as a whole, avoiding all the surprises of configuring them separately back- and forwards compatible.

I think it is irresponsible to not take the supposed infrastructure into the core unit of testing with that in mind.

Interesting! In trunk-based CI/CD with immutable production, you’d see if code is deploy-ready, then push artifact, and later deploy artifact. Keeping them discreet separate parts to keep things modularized and avoid entanglements.

In Lambda, you build immediately and deploy immediately, likely to test/stage first, then with confidence to production. The later deploy is likely a blue/green switch, such as change route or hostname to point to newly deployed service that passed the tests.

As far as I can see, both cases infrastructure can be included into core unit of testing, but isn’t always the case. In Lambda, the infrastructure to support Lambda is not exposed, and kept hidden, but external parts (RDS, SQS, SNS, S3, etc) could be provisioned. The same is true with Kubernetes, if you use a service broker to provision external AWS resources as part of deploying K8S objects, and you’d wouldn’t want to deploy K8S per application.

In most practices, infra is not always baked into core unit of testing, especially w/ mutable production, where infrastructure scripts (CFN or Terraform) and change config (chef/ansible/puppet/saltstack) are kept separated.

If would be interesting to see if Azure or Google Cloud would support SAM, or if there’s a solution to output Terraform instead of CloudFormation, and of course any movement to do something similar for non-lambda.