81

My question is about cleaning up the "Environments" tab on a Github repository.

I previously deployed via Heroku, using automatic deployment from two separate Github branches (one for staging, one for production).

This created a tab "Environments" on the repository, in which both Heroku environments were shown - exactly as intended.

Once I started to dive into Heroku pipelines, I have now configured the app to be promoted to production from staging, so the production environment no longer auto-deploys from a branch.

The Environments tab on my Github repo has no way to remove the environment that I no longer use. I can't seem to find any place on Github or Heroku to make Github "forget" this deployment environment.

I hope my question is clear enough; if I can elaborate on anything, please let me know.

mathiscode
  • 1,509
  • 3
  • 13
  • 10
  • 3
    I've got a similar issue. I have an environment on my project and I'm not sure how it got created. I'd like to remove it and I did not find how so far. – Alexis.Rolland Dec 11 '18 at 12:18
  • 3
    @Alexis.Rolland I believe they're automatically created via webhooks and I'm beginning to think it's a limitation of Github that prevents removing them. I really wish they'd add the option though. – mathiscode Dec 11 '18 at 17:49
  • 2
    Yup, had the same issue, and find it very annoying there is no way to do it! In my situation, I had a poorly configured environment wiping out my personal page. Ultimately, I just wound up reverting to a previous commit (the environment is still there though) – information_interchange Feb 25 '19 at 08:52
  • 2
    I'm having the same problem. I used a Heroku environment once and now have a permanent "Environments" tab on my repo I can't figure out how to get rid of. – Aaron Mar 11 '19 at 00:10
  • 5
    They should implement this asap – bpoiss May 08 '19 at 11:50
  • 1
    Here's a thread to follow with official replies on the GitHub Community forum - https://github.community/t5/GitHub-Pages/How-to-remove-the-environment-tab/m-p/24145 – Taylor D. Edmiston May 21 '19 at 23:39
  • 1
    go to settings -> environments now you can delete the environment – suhailvs Mar 16 '21 at 00:50

13 Answers13

62

There doesn't seem to be UI for it, but you can do it using the GitHub API.

You should probably disconnect GitHub and Heroku before doing this.

First, go to your GitHub account settings, then developer settings, then personal access tokens. Create a new token that has repo_deployments allowed. After it's generated, save the hexadecimal token, you'll need it for the upcoming API requests.

For these examples I'll assume that your username is $aaaa and your repo name is $bbbb and your access token is $tttt. Replace these with your actual username and repo name and access token. Or just use shell variables to store the actual values which will let you paste the code blocks directly.

First, list all the deployments on your repo:

curl https://api.github.com/repos/$aaaa/$bbbb/deployments

Each deployment has an id integer. Note it, and replace $iiii in the upcoming code blocks with that ID. Or create another shell variable for it.

Now you have to create an "inactive" status for that deployment:

curl https://api.github.com/repos/$aaaa/$bbbb/deployments/$iiii/statuses -X POST -d '{"state":"inactive"}' -H 'accept: application/vnd.github.ant-man-preview+json' -H "authorization: token $tttt"

And now you can delete the deployment forever:

curl https://api.github.com/repos/$aaaa/$bbbb/deployments/$iiii -X DELETE -H "authorization: token $tttt"

If you have multiple deployments, send the first request to see all the deployments that remain, and then you can delete those too if you want.

After you delete all the deployments, the environments button on the GitHub repo will disappear.

Information sourced from the GitHub deployments documentation and the GitHub oauth documentation. This worked for me.

Cadence
  • 746
  • 5
  • 12
  • Thanks for the script, I just tried it to delete my gh-pages deployments but it doesn't seem to have any effect, the requests are made but no changes appear on the repository. – Fez Vrasta Apr 30 '20 at 12:22
  • 1
    Thank you. I could generate the `tttt` access token, by going to the account settings > Developer settings > Personal access tokens, and generate one for 'repo' scope. – 0__ Jun 25 '20 at 06:57
  • just to add when you are using `curl` to delete the deployment. Make sure the headers are in double qoutes ex `"Authorization: token "` – Ryan Aquino Jul 15 '20 at 04:09
  • Using @Cadence's answer, I made a quick & dirty python3 script to automate the process. Just run it and enter your information, and all deployments will be removed, deleting the "Deployments" tab from your repo. See this gist: https://gist.github.com/ewen-lbh/30f8237e218b14f0f40ca5ed13bf24d6 – ewen-lbh Apr 18 '20 at 10:58
  • If you're using PowerShell, you might get `Problems parsing JSON` in the second command: replace `'{"state":"inactive"}'` with ``"{\`"state\`":\`"inactive\`"}"`` – nasso Jul 06 '22 at 23:06
62

I made a little webpage/script too, to automate the process (I don't have Python installed, and I didn't see that someone else had already made a script), and this is online and putting your info will do the process automatically.

Stackblitz - Github Deployments deleter

Edit 18/07/2020: I copied the script from Stackblitz to a local snippet code in here too, just in case Stackblitz disappears:

// RECOMMENDED: Disconnect HEROKU from Github before doing this (though not strictly necessary, I think).
//See https://stackoverflow.com/a/61272173/6569950 for more info.

// PARAMETERS
const TOKEN = ""; // MUST BE `repo_deployments` authorized
const REPO = "your-repo"; // e.g. "monorepo"
const USER_OR_ORG = "your-name"; // e.g. "your-name"

// GLOBAL VARS
const URL = `https://api.github.com/repos/${USER_OR_ORG}/${REPO}/deployments`;
const AUTH_HEADER = `token ${TOKEN}`;

// UTILITY FUNCTIONS
const getAllDeployments = () =>
  fetch(`${URL}`, {
    headers: {
      authorization: AUTH_HEADER
    }
  }).then(val => val.json());

const makeDeploymentInactive = id =>
  fetch(`${URL}/${id}/statuses`, {
    method: "POST",
    body: JSON.stringify({
      state: "inactive"
    }),
    headers: {
      "Content-Type": "application/json",
      Accept: "application/vnd.github.ant-man-preview+json",
      authorization: AUTH_HEADER
    }
  }).then(() => id);

const deleteDeployment = id =>
  fetch(`${URL}/${id}`, {
    method: "DELETE",
    headers: {
      authorization: AUTH_HEADER
    }
  }).then(() => id);

// MAIN
getAllDeployments()
  .catch(console.error)
  .then(res => {
    console.log(`${res.length} deployments found`);
    return res;
  })
  .then(val => val.map(({
    id
  }) => id))
  .then(ids => Promise.all(ids.map(id => makeDeploymentInactive(id))))
  .then(res => {
    console.log(`${res.length} deployments marked as "inactive"`);
    return res;
  })
  .then(ids => Promise.all(ids.map(id => deleteDeployment(id))))
  .then(res => {
    console.log(`${res.length} deployments deleted`);
    return res;
  })
  .then(finalResult => {
    const appDiv = document.getElementById("app");
    appDiv.innerHTML = `
<h1>CLEANUP RESULT</h1>
<br>
Removed Deployments: ${finalResult.length}
<br>
<br>Ids:<br>
${JSON.stringify(finalResult)}
<br><br><br><br><br><br>
  <p>(Open up the console)</p>
`;
  });
h1,
h2 {
  font-family: Lato;
}
<div id="app">
  <h1>Github Deployment's Cleaner</h1>
  <p> You need to put the parameters in!</p>
</div>
spersico
  • 846
  • 10
  • 15
  • 3
    How to get token? – Dmitrij Polyanin Apr 30 '20 at 12:24
  • 4
    you can generate one from https://github.com/settings/tokens . Remember to add the "repo_deployments" permission – spersico Apr 30 '20 at 16:09
  • Requires an update to `index.html`, and then won’t work for private repos. – mxcl Jun 05 '20 at 12:18
  • 1
    Thank you for this tool! There is a small bug in the code, the getAllDeployments fetch should look like the following: `fetch(`${URL}`, {headers: { authorization: AUTH_HEADER }}).then(val => val.json());` (headers object). Otherwise you won't be able to delete deployments for private repos – josias Jun 19 '20 at 13:18
  • 4
    Be careful, the script is launched automatically and removes all the deployments. I, as the question author, wanted to remove only particular environment, i.e. all the deployments for that environment. So I had to adjust the script to filter deployments by `.environment` property. – AKd Jul 04 '20 at 13:37
  • 5
    Also, the script gets only 30 recent deployments. In order to get to the old ones, you have to add `?per_page=100` parameter to the URL when getting the deployments. If your deployment is beyond recent 100, you have to paginate: https://docs.github.com/en/rest/guides/traversing-with-pagination. – AKd Jul 04 '20 at 13:39
  • 1
    For completeness, in addition to providing a link to your script, I encourage you to edit your answer to include the code here on Stack Overflow. – Chunky Chunk Jul 18 '20 at 18:32
  • 3
    I've created for simplicity a web page based on @spersico js snippet, i've also added an option to keep the last deployment (just in case you need it): https://githubdeploycleaner.herokuapp.com The code is here: https://githubdeploycleaner.herokuapp.com/res/cleaner.js – devpelux Jul 15 '21 at 12:28
  • 1
    Based on the snippet @spersico provided, I made a small node.js app, and added a small improvement as well. Original snippet only removes 30 deployments at a time. Below one runs until it removes all the deployments. https://github.com/crazyoptimist/remove-github-environment – crazyoptimist Jun 24 '22 at 09:58
  • Thank you so much it's one of question who solve what i want – Kashif Nov 17 '22 at 14:44
  • New link here https://devpelux.github.io/devpelux/githubdeploycleaner/ Heroku does not allow free hosting anymore, so i have migrated to github pages. Works the same as before. – devpelux Feb 17 '23 at 16:04
21

This will not answer the OP question, I thought it would at first, but it didn't behave as I had expected. Therefore, I'm adding this answer as a community wiki.

GitHub seems to have two notions of "Environments", the one the OP means are "public environments", but GitHub also seems to have some kind of "private environments".

I'm adding my experience as an answer below because it is really confusing.


You can access "private environments" through "Settings > Environments". (E.g: https://github.com/UnlyEd/next-right-now/settings/environments)

enter image description here

You can then delete each environment. It'll prompt a confirm dialog. Upon confirm, the environment will be destroyed.

enter image description here

I deleted the "staging" and "production" environments.

enter image description here

But the public environments still continue to exist, alongside all their deployments. (and this is not what the OP wants)

Public environments still contains "staging" and "production".

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
9

Based on Cadence's answer, I built the following bash script. Just set the appropriate parameters and let it run.

The token requires repo_deployment OAuth scope.

env=asd
token=asd
repo=asd
user=asd

for id in $(curl -u $user:$token https://api.github.com/repos/$user/$repo/deployments\?environment\=$env | jq ".[].id"); do
    curl -X POST -u $user:$token -d '{"state":"inactive"}' -H 'accept: application/vnd.github.ant-man-preview+json' https://api.github.com/repos/$user/$repo/deployments/$id/statuses
    curl -X DELETE -u $user:$token https://api.github.com/repos/$user/$repo/deployments/$id
done
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Fabio Poloni
  • 8,219
  • 5
  • 44
  • 74
  • 2
    Thanks. This requires that [jq](https://stedolan.github.io/jq/) is installed: `sudo apt install jq` – 0__ Jun 25 '20 at 07:19
9

I've made an interactive python script which can delete specific environments by name (which was my issue) or all of your deployments. Check it out and let me know if it works for you: https://github.com/VishalRamesh50/Github-Environment-Cleaner.

This will also actually delete all of your deployments even if you have more than 30 unlike the other scripts here because it goes through the paginated response data from Github's API and doesn't just use the first page.

Vishal Ramesh
  • 111
  • 1
  • 7
8

I Expect Your already got the answer for your question This answer is for those who wan't to Remove The Environments Tab from There GitHib Repo

As I Understand

  • If You Want to Remove the Environments Tab Shown on The Right Side of The Screen
  • If You Want to Remove Specific Environments

Remove Environments Tab

To Remove Entire Tab
  1. On Your Repo Page Click on Settings Button
  2. Uncheck the Mark on Environments

It Will Remove The Environments Tab from the Right Side

Remove Specific Environments

For Removing Specific Environment
  1. Click on Settings
  2. Click On Environments
  3. Here You Can Remove a Specific Environment

Reply from GitHub for Removing of Environments from Private Repo

Hi Deekshith,

Thanks for writing in!

As it turns out, the Environments feature is an enterprise-only feature for private repositories, however, they still get created as a side effect of Deployments in private repositories.

https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment

This means that though you'd be able to create Deployments in a private repository, you won't be able to manage (e.g delete, add rules e.t.c) the deployment Environments. I'm afraid this is currently the expected behaviour. Our engineers are still discussing how best to help users who'd want to delete environments in non-enterprise private repositories, such as in your case. We’ll be sure to update you as soon as there’s any news to share.

Sorry that we could not be of more help with this -- please let us know if you have any questions at all!

Regards,
Peter
GitHub Support

DeekshithSH
  • 173
  • 2
  • 8
  • unfortunately the "Environments" section is missing on my repo... [image](https://i.imgur.com/3VqXzMe.png) – cfaz Jun 21 '22 at 14:16
  • For a reason, the tab is not visible on private repositories, even if environments are supported. I was able to access the tab by making my project public to delete unused environments. but after switching my repo back to private, the deleted environments are back... – cfaz Jun 21 '22 at 14:33
  • 1
    @cfaz now i noticed it. if i found a way to remove the Environments in Private repo i will edit the Answer and Commet it – DeekshithSH Jun 22 '22 at 13:36
  • 1
    @cfaz can't remove Environments from a Private Repo. For the Reply from GitHub check the Answer – DeekshithSH Jun 28 '22 at 10:02
5

I've built an online tool to help out removing deployments

I ran into the same problem and found @spersico's code very handy, but needed a bit more tooling/feedback. I iterated on @spersico code to add a bit of frontend. Same as @spersico's version, all calls are made client side (and are visible in your console/network logs).

Project is opensource on Github and has a hosted version on Netlify which can be used instantly: https://github-deployment-cleaner.netlify.app/

Jaap
  • 1,079
  • 10
  • 11
3

Unfortunately, it seems that the 'Deployments' dashboard is currently in beta, which means that they may not have a feature yet.

Read here.

3

I've just used this Python script: 5 minutes and I removed my unwanted environment:

https://github.com/VishalRamesh50/Github-Environment-Cleaner

There is a discussion in GitHub Community: https://github.community/t/how-to-remove-the-environment-tab/10584/10?u=aerendir

Please, vote up the feature.

Aerendir
  • 6,152
  • 9
  • 55
  • 108
2

Using GitHub CLI:

org=':org:'
repo=':repo:'
env=':env:'

gh api "repos/${org}/${repo}/deployments?environment=${env}" \
  | jq -r ".[].id" \
  | xargs -n 1 -I % sh -c "
  gh api -X POST -F state=inactive repos/${org}/${repo}/deployments/%/statuses
  gh api -X DELETE repos/${org}/${repo}/deployments/%
"
gabrielf
  • 2,210
  • 1
  • 19
  • 11
kjagiello
  • 8,269
  • 2
  • 31
  • 47
  • 1
    Perfect! Other solutions mentioned haven't worked for me as the environments tab doesn't exist and the `setting/environments` url doesn't return a page. Didn't know gh could be used for general api requests, good to know! – gabrielf Jun 01 '22 at 12:31
1

I don't know if this was posted already but I definitely didn't want do delete my 40+ deployments manually so I created following script, feel free to use it too :)

#!/bin/bash

REPO=<your GH name>/<your project name>
TOKEN=<your personal access token>

# https://starkandwayne.com/blog/bash-for-loop-over-json-array-using-jq/
for deployment in $(curl https://api.github.com/repos/$REPO/deployments | jq -r '.[] | @base64'); do
    DEPLOYMENT_ID=$(echo "$deployment" | base64 --decode | jq -r '.id')
    echo "$DEPLOYMENT_ID"
    curl "https://api.github.com/repos/$REPO/deployments/$DEPLOYMENT_ID/statuses" \
        -X POST \
        -d '{"state":"inactive"}' \
        -H 'accept: application/vnd.github.ant-man-preview+json' \
        -H "authorization: token $TOKEN"
done
for deployment in $(curl https://api.github.com/repos/$REPO/deployments | jq -r '.[] | @base64'); do
    DEPLOYMENT_ID=$(echo "$deployment" | base64 --decode | jq -r '.id')
    curl "https://api.github.com/repos/$REPO/deployments/$DEPLOYMENT_ID" \
        -X DELETE \
        -H "authorization: token $TOKEN"
done
D3strukt0r
  • 571
  • 1
  • 4
  • 19
1

You can remove the environment from a repository if its public. But in case of private repositories, either you have to make it public or use the github API. Both works, but here is my approach for deleting the environments.

I created an npm package (here) for the same. Just get the github access token, with repo_deployments scope enabled.

Now run npx delete-github-environment and select the environment that you want to delete. If everything went right, your environment will be deleted.

PS: Here's my github repo - (github), feel free to contribute to the code.

1

To remove a Github Environment go to Settings -> Environments -> and click the trashcan icon next to the Environment you want to delete (see picture below).

More can be read about it from the Github official documentation: Deleting an Environment

GitHub Environments

David Asbill
  • 128
  • 5