Created
October 30, 2023 12:03
-
-
Save karimelmel/f229d3194592c3cd3f21367204bfa5fa 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
import requests | |
import json | |
import os | |
def add_secrets_to_environments(github_token, org_or_user, repositories_file): | |
with open(repositories_file, "r") as json_file: | |
repos_data = json.load(json_file) | |
repositories = repos_data.get("repositories", []) | |
for repo in repositories: | |
repo_name = repo["repo_name"] | |
environments = repo.get("environments", []) | |
for environment in environments: | |
environment_name = environment.get("name", "") | |
secrets = environment.get("secrets", []) | |
if not environment_name: | |
continue | |
for secret in secrets: | |
secret_name = secret.get("secret_name", "") | |
secret_value = secret.get("secret_value", "") | |
if not secret_name or not secret_value: | |
continue | |
add_secret_to_environment(github_token, org_or_user, repo_name, environment_name, secret_name, secret_value) | |
def add_secret_to_environment(github_token, org_or_user, repo_name, environment_name, secret_name, secret_value): | |
base_url = f"https://api.github.com/repos/{org_or_user}/{repo_name}/environments/{environment_name}/secrets" | |
headers = { | |
"Authorization": f"Bearer {github_token}", | |
"Accept": "application/vnd.github.v3+json", | |
"X-GitHub-Api-Version": "2022-11-28", | |
} | |
data = { | |
"encrypted_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 '{repo_name}'.") | |
else: | |
print(f"Failed to add secret '{secret_name}' to environment '{environment_name}' for repository '{repo_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") | |
repository = os.environ.get("REPOSITORY") | |
if not github_token or not org_or_user or not repository: | |
raise ValueError('One or more required environment variables are not set.') | |
add_secrets_to_environments(github_token, org_or_user, repository) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment