Skip to content

Instantly share code, notes, and snippets.

@nazartm
Last active January 24, 2023 09:17
Show Gist options
  • Save nazartm/1ee75b4a654d3455caf03105c2ae0177 to your computer and use it in GitHub Desktop.
Save nazartm/1ee75b4a654d3455caf03105c2ae0177 to your computer and use it in GitHub Desktop.
Python script for adding Actions secrets to a Github repository
from base64 import b64encode
from nacl import encoding, public
import requests
MY_PAC = ''
ORG = 'MyOrg'
REPO = 'repo'
secrets = {
'TOOL_USER': 'admin',
'TOOL_PASS': 'secret-value'
}
def get_public_key():
headers = {'Accept': 'application/vnd.github+json', 'Authorization': "Bearer " + MY_PAC}
response = requests.get("https://api.github.com/repos/{}/{}/actions/secrets/public-key".format(ORG, REPO), headers = headers)
return response.json()
def encrypt(public_key: str, secret_value: str) -> str:
"""Encrypt a Unicode string using the public key."""
public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder())
sealed_box = public.SealedBox(public_key)
encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
return b64encode(encrypted).decode("utf-8")
def create_secret(secret_name, value, public_key):
headers = {'Accept': 'application/vnd.github+json', 'Authorization': "Bearer " + MY_PAC}
data = {"encrypted_value": encrypt(public_key['key'], value ), "key_id": public_key['key_id']}
response = requests.put("https://api.github.com/repos/{0}/{1}/actions/secrets/{2}".format(ORG, REPO, secret_name), headers = headers, json = data)
return response.status_code
print("Retrieving public key for repository {}".format(REPO))
public_key = get_public_key()
for k, v in secrets.items():
print("Creating secret for {}".format(k))
print(create_secret(k, v, public_key))
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment