Learn Continuous Deployment with Bitbucket Pipelines

We'll see in this guide how you can implement a continuous deployment pipeline with Bitbucket Pipelines.

Sten Pittet Sten Pittet

Em desenvolvimento de software, você com frequência precisa realizar concessões difíceis ao desenvolver um aplicativo. Se quiser ir mais rápido, a crença geral é que precisará abrir mão da qualidade de suas versões. Porém, há uma prática de desenvolvimento que pode lhe permitir poupar tempo enquanto lança mais rapidamente: implementação contínua.

Com a implementação contínua, você elimina o estresse de implementar software tornando-o um processo automatizado. Sua equipe de desenvolvimento não precisa mais parar e mudar o contexto para uma versão – o código é enviado aos seus clientes assim que um desenvolvedor tiver terminado o trabalho.

We'll see in this guide how you can implement a continuous deployment pipeline with Bitbucket Pipelines.

Entrega contínua vs. implementação contínua

Continuous delivery is the practice of making sure that your code is always ready to release even if you are not deploying every change to production. It is recommended to update your production as often as possible to make sure that you keep the scope of the changes small, but ultimately you're in control the rhythm of your releases.

In continuous deployment, new changes pushed to the repository are automatically deployed to production if they pass the tests. This puts more emphasis (read: pressure) on your testing culture, but it's a great way to accelerate the feedback loop with your customers.

Diagram showing the difference between continuous deployment and continuous development | Atlassian CI/CD

Requisitos

Tempo:

30 minutes

 

Público-alvo:

You are new to continuous deployment and/or Bitbucket Pipelines

 

Pré-requisito:

Experimente grátis

Configurando um pipeline de implementação contínua

Continuous deployment is a great way for teams to accelerate development. It removes the impediments related to the release approval process, and it allows developers to get feedback from customers as soon as they're done with their work. Issues are easier to identify and fix, and there's less context switching as there's no release time anymore.

Configuring a continuous deployment pipeline with Bitbucket Pipelines is very easy. We will see how to do it with a simple Hello World application that goes through a staging environment and acceptance tests before getting released automatically to production.

You can find the source of the Hello World app in the repository linked below.

Preparando a implementação para o Heroku

Before we begin we need to add a few environment variables to be able to deploy our application on Heroku:

  • HEROKU_API_KEY: You can find your API key in your Heroku account
  • HEROKU_STAGING: nome do seu ambiente de preparação
  • HEROKU_PROD: nome do seu ambiente de produção

Go to Pipelines > Environment variables in your repository settings to add the variables.

Configuração de variáveis de ambiente para implementar no Heroku

Configuração de variáveis de ambiente para implementar no Heroku

We're using Heroku in this guide, it is certainly possible to adapt this example to other hosting services. You can find other deployment guides in the documentation.

Configuração do pipeline

Nosso fluxo de trabalho será simples:

  • Compilar o aplicativo.
  • Executar testes no build.
  • Implementar para staging.
  • Executar alguns testes de aceitação no staging.
  • Deploy to production.

You'll see that it's very easy to create the corresponding pipeline configuration. We'll start by adding our automatic deployment to the staging environment to make sure that it's happening properly on every push.

image: node:4.6.0   # Doing a full clone to be able to push back to Heroku. clone:   depth: full   pipelines:   branches:     master:       - step:           script: # Modify the commands below to build your repository.             - npm install             - npm test             - git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_STAGING.git master  

You'll notice that we're using a full clone to make sure that Heroku doesn't reject our push. Then we're also using a branch-specific pipeline to make sure that we only deploy staging for changes pushed on master and not on other branches. You can push this configuration to Bitbucket to see it in action.

A implementação automática para staging está concluída


Nesse estágio, agora temos nosso aplicativo Olá, Mundo implementado em staging.

We can now move on to the next step and add our acceptance tests. Acceptance tests are here to make sure that our application behaves as expected in a production-like environment (staging). The goal is to remove uncertainties due to differences in configuration between the environment used to test the build and your production.

If you look at the code of our app our test is doing something extremely simple as it's just looking for the presence of the string "Hello World" in the page. In a real application we recommend to have acceptance tests that go much further and verify that all the underlying services used by your application (database, cache, 3rd party, etc.) are working properly.

So let's add our test right after our deployment to staging.

image: node:4.6.0   # Doing a full clone to be able to push back to Heroku. clone:   depth: full   pipelines:   branches:     master:       - step:           script: # Modify the commands below to build your repository.             - npm install             - HEROKU_STAGING=$HEROKU_STAGING npm test acceptance-test             - git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_STAGING.git master             - npm test acceptance-test  

Depois de enviar esta nova configuração para o Bitbucket, podemos ver nosso pipeline ser concluído com sucesso.

O Bitbucket Pipelines agora executa testes de aceitação depois de implementar para preparação

All that is left now is to add our production deployment at the end to complete our continuous deployment pipeline.

image: node:4.6.0   # Doing a full clone to be able to push back to Heroku. clone:   depth: full   pipelines:   branches:     master:       - step:           script: # Modify the commands below to build your repository.             - npm install             - npm test             - git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_STAGING.git master             - HEROKU_STAGING=$HEROKU_STAGING npm test acceptance-test             - git push https://heroku:$HEROKU_API_KEY@git.heroku.com/$HEROKU_PROD.git master  

A final push to Bitbucket will take our code changes through all the pipeline, building and testing the code then deploying to production after successfully verifying that staging works. In this case the homepage has been updated with a different message to make sure that it would get deployed all the way to production.

Our new message went to production as expected!

You can check the pipeline to make sure that it went properly through all the different phases.

Verificando se o código passou pelo pipeline

É importante destacar a relevância de ter um bom pacote de teste, bem como de ter monitoramento em tempo real em vigor antes de seguir em frente e aplicar implementação contínua para seus próprios repositórios. De agora em diante, as alterações vão direto para produção assim que são enviadas ao branch principal. Assim, é ainda mais importante garantir que seus testes automatizados verifiquem as partes fundamentais do seu aplicativo. Além disso, você precisará de ferramentas de monitoramento para detectar alterações que afetem negativamente suas instâncias de produção, seja uma falha total ou um serviço degradado.

Você pode encontrar a fonte final no repositório do Bitbucket Cloud vinculado abaixo.