Answers: <p>In a typical Continuous Delivery/Deployment pipeline you would have the following happen:</p>
  
  <ol>
  <li>Developer pushes one or more commits, or, a pull request is merged.</li>
  <li>Jenkins automatically builds and executes tests.</li>
  <li>If successful Jenkins publishes a deployment package to an Artefact Repository; if failure publishes nothing and notify developers.</li>
  <li>Deployment automation uses packages from the Artefact Repository and deploys them.</li>
  </ol>
  
  <p><a href="https://i.sstatic.net/xy8NS.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/xy8NS.png" alt="Simple CI/CD Pipeline"></a></p>
  
  <p>The goal is to avoid <strong>building</strong> the solution from source twice, you build it once and deploy it many times.  You can implement approvals in <a href="https://www.sonatype.com/nexus-repository-sonatype" rel="nofollow noreferrer">Sonartype Nexus</a> to define the environment approval process, i.e. Dev → Test → UAT → Stage → Production.</p>
  
  <p><strong>That said...</strong> if you have read all of the previous and still want to get the latest green build from source control then you can use one of two techniques:</p>
  
  <ol>
  <li>Have Jenkins tag the branch with a suitably named tag, i.e. <code>master-green</code> then use that instead of <code>master</code> when you want the latest green build.</li>
  <li>Use the BitBucket <a href="https://api.bitbucket.org/2.0/repositories/tutorials/tutorials.bitbucket.org/commits" rel="nofollow noreferrer">commits</a> to get a list of commits and <a href="https://api.bitbucket.org/2.0/repositories/tutorials/tutorials.bitbucket.org/commit/f25983afbdd4d09811fe750d53d3ff7a857f941b/statuses" rel="nofollow noreferrer">commit/{sha}/statuses</a> over each one to find the commit with a Green status.  I have expanded on this solution in <a href="https://devops.stackexchange.com/a/832/397">another answer</a>.</li>
  </ol>
  
  <p>Feel free to post a follow-up question if you would like the specific detail on how to use the above approaches.</p>
  
Answers: CC BY-SA 3.0
Answers: 2017-04-08T22:26:00.327Z
Answers: 2017-04-10T17:02:10.660Z
Answers: 2017-04-13T13:01:29.297Z
Answers: Richard Slater
Answers: <p>You don't make any mention of the scripting language you want to use, so I will talk specifically about the HTTP requests to the BitBucket API:</p>
  
  <h2>Assumptions</h2>
  
  <p>If you have a <a href="https://bitbucket.org/RichardSlater/greencommitproofofconcept" rel="noreferrer">BitBucket Repository</a> that has three commits in in it the first and the last are failing the build, the middle is passing:</p>
  
  <ul>
  <li>4768815 ❌</li>
  <li>49d7110 ✅</li>
  <li>42d357f ❌</li>
  </ul>
  
  <h2>Get the list of commits</h2>
  
  <p>You can get the list of commits by calling the following API method:</p>
  
  <blockquote>
    <p><code>https://api.bitbucket.org/2.0/repositories/{{owner}}/{{repo_slug}}/commits</code></p>
    
    <ul>
    <li><code>owner</code>: RichardSlater</li>
    <li><code>repo_slug</code>: greencommitproofofconcept</li>
    </ul>
  </blockquote>
  
  <p>The response looks like this:</p>
  
  <pre><code>{
    "pagelen": 30,
    "values": [
      {
        "hash": "4768815fdc27abf4be17096e7c460f7f68f5d39b",
        "repository": { ... },
        "links": {
          ...
          "statuses": {
            "href": "https://api.bitbucket.org/2.0/repositories/RichardSlater/greencommitproofofconcept/commit/4768815fdc27abf4be17096e7c460f7f68f5d39b/statuses"
          }
        },
        "author": { ... },
        "parents": [ ... ],
        "date": "2017-04-10T11:38:18+00:00",
        "message": "README.md edited online with Bitbucket",
        "type": "commit"
      },
      {
        "hash": "49d7110b98616358d16055960a4abdf2926b890d",
        ...
      },
      {
        "hash": "42d357f1df7a7d7bcf1f10a9f3a5a40d85d5b11c",
        ...
      }
    ]
  }
  </code></pre>
  
  <p>If you parse the JSON and loop over the responses you can extract out the statuses from:</p>
  
  <pre><code>values[n].links.statuses.href
  </code></pre>
  
  <p>Where <code>n</code> is the index, i.e. <code>0</code>, <code>1</code> or <code>2</code> in the above example.  If you were to construct this from scratch it would be in the following format.</p>
  
  <h2>Get the list of statuses from the commit</h2>
  
  <blockquote>
    <p><code>https://api.bitbucket.org/2.0/repositories/{{owner}}/{{repo_slug}}/commit/{{sha}}/statuses"</code></p>
    
    <ul>
    <li><code>owner</code>: RichardSlater</li>
    <li><code>repo_slug</code>: greencommitproofofconcept</li>
    <li><code>sha</code>: 4768815fdc27abf4be17096e7c460f7f68f5d39b</li>
    </ul>
  </blockquote>
  
  <p><strong>Note:</strong> this is a Hypermedia API which means the urls <em>could</em> change so I would recommend using the links from the previous response rather than trying to generate them from scratch.</p>
  
  <p>The response from the above HTTP request will be something like:</p>
  
  <pre><code>{
    "pagelen": 10,
    "values": [
      {
        "key": "POC-01",
        "name": "Build #1",
        "repository": { ... },
        "url": "http://devops.stackexchange.com/q/809/397",
        "links": { ... },
        "refname": null,
        "state": "FAILED",
        "created_on": "2017-04-10T13:04:28.261734+00:00",
        "updated_on": "2017-04-10T13:04:28.261759+00:00",
        "type": "build",
        "description": "Changes by Richard Slater"
      }
    ],
    "page": 1,
    "size": 1
  }
  </code></pre>
  
  <p>From this response you can extract the <code>state</code> using:</p>
  
  <pre><code>values[n].state
  </code></pre>
  
  <p>Again where <code>n</code> is the <code>status</code> - there could be many of them if one commit resulted in many builds.</p>
  
  <p>If the state for the build you care about is <code>SUCCESSFUL</code> then you have your answer and you can immediately return the <code>sha</code> for the commit.</p>
  
  <p>Loop over all of the commits from the first phase, if you run out of commits follow the <code>next</code> page <code>link</code> that is included in the call to <code>/commits</code>.</p>
  
  <h2>Complete Flow Diagram</h2>
  
  <p>At a high level the flow will look like this:</p>
  
  <p><a href="https://i.sstatic.net/IMe8G.png" rel="noreferrer"><img src="https://i.sstatic.net/IMe8G.png" alt="Flow Diagram"></a></p>
  
  <p>Don't forget this is a <a href="https://looselyconnected.wordpress.com/2011/03/09/the-richardson-maturity-model-of-rest-and-roy-fielding/" rel="noreferrer">Hypermedia API</a> so wherever possible have your code follow the links in the API rather than trying to "guess them".</p>
  
Answers: CC BY-SA 3.0
Answers: 2017-04-11T08:51:52.887Z
Answers: Yes it does, it's probably my longest answer on SE ever.
Answers: Richard Slater
Answers: CC BY-SA 3.0
Answers: 2017-04-11T12:51:27.213Z
Answers: I appreciate the time you took to explain this even if you think I'm completely insane for wanting it. Accepted
Answers: Alex
Answers: CC BY-SA 3.0
Answers: 2017-04-11T12:56:58.980Z
Answers: Not completely insane, just taking your first few steps - keep my other answer in mind when you are thinking about CI/CD architectures.
Answers: Richard Slater
Answers: CC BY-SA 3.0
Answers: 2017-04-10T17:00:53.070Z
Answers: 2017-04-11T08:54:21.933Z
Answers: 2017-04-11T08:54:21.933Z
Answers: Richard Slater
Body: <p>We're just starting to push for CI-CD and as a baby step we're going to try updating a stack with the latest green develop once every couple of hours. I am fairly new to Git/Bitbucket, and can't figure out how to ensure the checkout that Jenkins makes gets the last commit to have been marked green by Jenkins, rather than just "the last commit" as a blanket statement. </p>
  
  <p>We have the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Bitbucket+Cloud+Build+Status+Notifier+Plugin" rel="noreferrer">Bitbucket Build Status Notifier</a> plugin installed, so Bitbucket does track which commits are green after our unit tests run. Is there a way to leverage this info to make sure the right commit is picked?</p>
  
Tags: <jenkins><git><bitbucket><bcbsn>
Title: Git & Jenkins: get latest green commit on branch
UserDisplayName: Alex
ThreadText: # Git & Jenkins: get latest green commit on branch
  
  (Asked by: username_0 on 2017-04-07)
  
  We're just starting to push for CI-CD and as a baby step we're going to try updating a stack with the latest green develop once every couple of hours. I am fairly new to Git/Bitbucket, and can't figure out how to ensure the checkout that Jenkins makes gets the last commit to have been marked green by Jenkins, rather than just "the last commit" as a blanket statement.
  
  We have the [Bitbucket Build Status Notifier](https://wiki.jenkins-ci.org/display/JENKINS/Bitbucket+Cloud+Build+Status+Notifier+Plugin) plugin installed, so Bitbucket does track which commits are green after our unit tests run. Is there a way to leverage this info to make sure the right commit is picked?
  
  **Tags:** jenkins, git, bitbucket, bcbsn
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_1 on 2017-04-10. Score: 7 | Accepted answer
  
  You don't make any mention of the scripting language you want to use, so I will talk specifically about the HTTP requests to the BitBucket API:
  
  ## Assumptions
  
  If you have a [BitBucket Repository](https://bitbucket.org/username_1/greencommitproofofconcept) that has three commits in in it the first and the last are failing the build, the middle is passing:
  
  * 4768815 ❌
  * 49d7110 ✅
  * 42d357f ❌
  
  ## Get the list of commits
  
  You can get the list of commits by calling the following API method:
  
  > `https://api.bitbucket.org/2.0/repositories/{{owner}}/{{repo_slug}}/commits`
  >
  > * `owner`: username_1
  > * `repo_slug`: greencommitproofofconcept
  
  The response looks like this:
  
  ```
  {
    "pagelen": 30,
    "values": [
      {
        "hash": "4768815fdc27abf4be17096e7c460f7f68f5d39b",
        "repository": { ... },
        "links": {
          ...
          "statuses": {
            "href": "https://api.bitbucket.org/2.0/repositories/username_1/greencommitproofofconcept/commit/4768815fdc27abf4be17096e7c460f7f68f5d39b/statuses"
          }
        },
        "author": { ... },
        "parents": [ ... ],
        "date": "2017-04-10T11:38:18+00:00",
        "message": "README.md edited online with Bitbucket",
        "type": "commit"
      },
      {
        "hash": "49d7110b98616358d16055960a4abdf2926b890d",
        ...
      },
      {
        "hash": "42d357f1df7a7d7bcf1f10a9f3a5a40d85d5b11c",
        ...
      }
    ]
  }
  
  ```
  
  If you parse the JSON and loop over the responses you can extract out the statuses from:
  
  ```
  values[n].links.statuses.href
  
  ```
  
  Where `n` is the index, i.e. `0`, `1` or `2` in the above example. If you were to construct this from scratch it would be in the following format.
  
  ## Get the list of statuses from the commit
  
  > `https://api.bitbucket.org/2.0/repositories/{{owner}}/{{repo_slug}}/commit/{{sha}}/statuses"`
  >
  > * `owner`: username_1
  > * `repo_slug`: greencommitproofofconcept
  > * `sha`: 4768815fdc27abf4be17096e7c460f7f68f5d39b
  
  **Note:** this is a Hypermedia API which means the urls *could* change so I would recommend using the links from the previous response rather than trying to generate them from scratch.
  
  The response from the above HTTP request will be something like:
  
  ```
  {
    "pagelen": 10,
    "values": [
      {
        "key": "POC-01",
        "name": "Build #1",
        "repository": { ... },
        "url": "http://devops.stackexchange.com/q/809/397",
        "links": { ... },
        "refname": null,
        "state": "FAILED",
        "created_on": "2017-04-10T13:04:28.261734+00:00",
        "updated_on": "2017-04-10T13:04:28.261759+00:00",
        "type": "build",
        "description": "Changes by username_1"
      }
    ],
    "page": 1,
    "size": 1
  }
  
  ```
  
  From this response you can extract the `state` using:
  
  ```
  values[n].state
  
  ```
  
  Again where `n` is the `status` - there could be many of them if one commit resulted in many builds.
  
  If the state for the build you care about is `SUCCESSFUL` then you have your answer and you can immediately return the `sha` for the commit.
  
  Loop over all of the commits from the first phase, if you run out of commits follow the `next` page `link` that is included in the call to `/commits`.
  
  ## Complete Flow Diagram
  
  At a high level the flow will look like this:
  
  [![Flow Diagram](https://i.sstatic.net/IMe8G.png)](https://i.sstatic.net/IMe8G.png)
  
  Don't forget this is a [Hypermedia API](https://looselyconnected.wordpress.com/2011/03/09/the-richardson-maturity-model-of-rest-and-roy-fielding/) so wherever possible have your code follow the links in the API rather than trying to "guess them".
  
  > **Comments:**
  > **username_1**: Yes it does, it's probably my longest answer on SE ever.  
  > **username_0**: I appreciate the time you took to explain this even if you think I'm completely insane for wanting it. Accepted  
  > **username_1**: Not completely insane, just taking your first few steps - keep my other answer in mind when you are thinking about CI/CD architectures.  
  
  ---
  
  ### Answer by username_1 on 2017-04-08. Score: 3
  
  In a typical Continuous Delivery/Deployment pipeline you would have the following happen:
  
  1. Developer pushes one or more commits, or, a pull request is merged.
  2. Jenkins automatically builds and executes tests.
  3. If successful Jenkins publishes a deployment package to an Artefact Repository; if failure publishes nothing and notify developers.
  4. Deployment automation uses packages from the Artefact Repository and deploys them.
  
  [![Simple CI/CD Pipeline](https://i.sstatic.net/xy8NS.png)](https://i.sstatic.net/xy8NS.png)
  
  The goal is to avoid **building** the solution from source twice, you build it once and deploy it many times. You can implement approvals in [Sonartype Nexus](https://www.sonatype.com/nexus-repository-sonatype) to define the environment approval process, i.e. Dev → Test → UAT → Stage → Production.
  
  **That said...** if you have read all of the previous and still want to get the latest green build from source control then you can use one of two techniques:
  
  1. Have Jenkins tag the branch with a suitably named tag, i.e. `master-green` then use that instead of `master` when you want the latest green build.
  2. Use the BitBucket [commits](https://api.bitbucket.org/2.0/repositories/tutorials/tutorials.bitbucket.org/commits) to get a list of commits and [commit/{sha}/statuses](https://api.bitbucket.org/2.0/repositories/tutorials/tutorials.bitbucket.org/commit/f25983afbdd4d09811fe750d53d3ff7a857f941b/statuses) over each one to find the commit with a Green status. I have expanded on this solution in [another answer](https://devops.stackexchange.com/a/832/397).
  
  Feel free to post a follow-up question if you would like the specific detail on how to use the above approaches.
  
  
  ---
  
  