Last active
October 30, 2023 11:54
-
-
Save karimelmel/73c0bed3d4bc4692a805aad7a63c7ef0 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
# add_secrets_to_environment.py | |
import requests | |
import os | |
import json | |
def add_secrets_to_environment(github_token, org_or_user): | |
# Load data from the repositories.json file | |
with open("repositories.json", "r") as json_file: | |
data = json.load(json_file) | |
# Get repositories from the data | |
repositories = data.get("repositories", []) | |
for repo in repositories: | |
repository_name = repo.get("repo_name") | |
environments = repo.get("environments", {}) | |
for environment_name, secrets in environments.items(): | |
base_url = f"https://api.github.com/repos/{org_or_user}/{repository_name}/environments/{environment_name}/secrets" | |
headers = { | |
"Authorization": f"Bearer {github_token}", | |
"Accept": "application/vnd.github.v3+json", | |
"X-GitHub-Api-Version": "2022-11-28", | |
} | |
for secret_name, secret_value in secrets.items(): | |
data = { | |
'name': secret_name, | |
'value': secret_value, | |
} | |
response = requests.put(base_url, headers=headers, json=data) | |
if response.status_code == 204: | |
print(f"Secret '{secret_name}' added to environment '{environment_name}' for repository '{repository_name}'.") | |
else: | |
print(f"Failed to add secret '{secret_name}' to environment '{environment_name}' for repository '{repository_name}'. Status code: {response.status_code}") | |
print(response.text) | |
if __name__ == "__main__": | |
github_token = os.environ.get("GITHUB_TOKEN") | |
org_or_user = os.environ.get("ORG_OR_USER") | |
if not github_token or not org_or_user: | |
raise ValueError('One or more required environment variables are not set.') | |
# Call the function to add secrets to the environments | |
add_secrets_to_environment(github_token, org_or_user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment