Created
May 4, 2022 13:15
-
-
Save nkammah/8868b755a079aa75d1abb86ce1fc8b77 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import click | |
from gql import gql, Client | |
from gql.transport.aiohttp import AIOHTTPTransport | |
class BuildkiteApi: | |
def __init__(self, token): | |
# Load buildkite data | |
transport = AIOHTTPTransport( | |
url="https://graphql.buildkite.com/v1", | |
headers={ | |
"Authorization": "Bearer " + os.environ.get("BUILDKITE_TOKEN", "") | |
}, | |
) | |
self.client = Client(transport=transport) | |
def users(self): | |
query = gql( | |
""" | |
query getUsage { | |
organization(slug: "elastic") { | |
members(first: 500) { | |
edges { | |
node { | |
id | |
user { | |
builds (first:1) { | |
edges { | |
node { | |
createdAt | |
url | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
""" | |
) | |
results = self.client.execute(query) | |
return results["organization"]["members"]["edges"] | |
def remove_user(self, user_id): | |
query = gql( | |
""" | |
mutation RemoveOrganizationMember { | |
organizationMemberDelete(input: { id: "%s" }) { | |
deletedOrganizationMemberID | |
} | |
} | |
""" | |
% user_id | |
) | |
return self.client.execute(query) | |
@click.command() | |
@click.option( | |
"--buildkite-token", | |
required=True, | |
envvar="BUILDKITE_TOKEN", | |
help="Buildkite API token.", | |
) | |
@click.option("--dry-run", is_flag=True) | |
def remove_inactive_users(buildkite_token, dry_run): | |
buildkite = BuildkiteApi(buildkite_token) | |
for bk_user in buildkite.users(): | |
if len(bk_user["node"]["user"]["builds"]["edges"]) == 0: | |
print("Removing inactive user %s" % bk_user["node"]["user"]["email"]) | |
if not dry_run: | |
buildkite.remove_user(bk_user["node"]["id"]) | |
if __name__ == "__main__": | |
remove_inactive_users() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment