Skip to content

Commit c6aa80b

Browse files
DEVOPS-41 update secrets from KV
1 parent 934c07e commit c6aa80b

10 files changed

+637
-2
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
name: Azure Auth and az account show
2+
3+
on:
4+
push:
5+
workflo_dispatch:
6+
7+
jobs:
8+
azure-auth:
9+
runs-on: ubuntu-latest
10+
11+
steps:
12+
- name: Checkout repository
13+
uses: actions/checkout@v2
14+
15+
- name: Set up Azure CLI
16+
uses: azure/CLI@v1
17+
18+
- name: Login via Azure CLI
19+
run: |
20+
az login --service-principal -u ${{ secrets.ARM_CLIENT_ID }} -p ${{ secrets.ARM_CLIENT_SECRET }} --tenant ${{ secrets.ARM_TENANT_ID }}
21+
az account set --subscription ${{ secrets.ARM_SUBSCRIPTION_ID }}
22+
az account show -o json
23+
24+
- name: Completed
25+
run: echo 'completed'

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ ipython_config.py
9999
# This is especially recommended for binary packages to ensure reproducibility, and is more
100100
# commonly ignored for libraries.
101101
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102-
#poetry.lock
102+
poetry.lock
103103

104104
# pdm
105105
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
@@ -159,4 +159,4 @@ cython_debug/
159159
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160160
# and can be added to the global gitignore or merged into this file. For a more nuclear
161161
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
162-
#.idea/
162+
.idea/

create_repo_secrets.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import requests
2+
import os
3+
from datetime import datetime
4+
import pytz
5+
6+
def current_ist_time():
7+
"""code to return time in IST"""
8+
# Get the current time in IST
9+
ist = pytz.timezone('Asia/Kolkata')
10+
ist_now = datetime.now(ist)
11+
12+
# Format and print the current time in IST
13+
ist_now_formatted = ist_now.strftime('%Y-%m-%d %H:%M:%S %Z%z')
14+
return ist_now_formatted
15+
16+
17+
def create_or_update_repository_secret_github(repo_name: str, secret_name: str, secret_value: str, public_key_id: int):
18+
"""
19+
Create or update org level secret in GitHub
20+
Ref https://docs.github.com/en/rest/actions/secrets?apiVersion=2022-11-28#create-or-update-an-organization-secret
21+
22+
The token must have the following permission set: organization_secrets:write
23+
"""
24+
encrypted_secret = secret_value
25+
organization = os.getenv('GITHUB_REPOSITORY_OWNER')
26+
27+
if not encrypted_secret:
28+
print("ENCRYPTED_SECRET environment variable is not set or is empty.")
29+
# print(f'encrypted sec is: {encrypted_secret}')
30+
ist_now_formatted = current_ist_time()
31+
github_repo_secret_endpoint = f"https://api.github.com/repos/{organization}/{repo_name}/actions/secrets/{secret_name}"
32+
33+
headers = {
34+
"Accept": "application/vnd.github+json",
35+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
36+
"X-GitHub-Api-Version": "2022-11-28"
37+
}
38+
data = {
39+
"encrypted_value": encrypted_secret,
40+
"visibility": "all",
41+
"key_id": public_key_id
42+
}
43+
response = requests.put(github_repo_secret_endpoint, headers=headers, json=data)
44+
if response.status_code == 201:
45+
print(f"Secret {secret_name} created on {repo_name} at {ist_now_formatted} ")
46+
else:
47+
print(f"Secret {secret_name} updated on {repo_name} at {ist_now_formatted} ")
48+
49+
50+
def main():
51+
"""To test the code"""
52+
53+
organization = os.getenv('organization')
54+
secret_name = os.getenv('secret_name')
55+
56+
# Function call
57+
create_or_update_repository_secret_github(organization, secret_name)
58+
59+
if __name__ == "__main__":
60+
main()

encrypt_using_libnacl.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Python script includes a function, encrypt, designed to encrypt Unicode strings using public-key cryptography through the PyNaCl library.
2+
# To utilize this functionality, begin by importing the necessary libraries with the from base64 import b64encode and from nacl import encoding,
3+
# public statements. Subsequently, define and call the encrypt function, passing a Base64-encoded public key and a Unicode string as parameters.
4+
# The function then encrypts the provided value using the public key and returns the result in a Base64-encoded format.
5+
# For example, calling encrypt("aSBhbSBrcmlzaG5hZGhhcwo=", "aSBhbSBrcmlzaG5hZGhhcwo=") demonstrates how to encrypt a sample Unicode string using a specified public key.
6+
# Ensure proper handling and security of public keys and secret values within your application.
7+
from get_repo_public_key import get_repository_public_key
8+
from base64 import b64encode
9+
from nacl import encoding, public
10+
import os
11+
12+
def encrypt(public_key: str, secret_value: str) -> str:
13+
"""Encrypt a Unicode string using the public key."""
14+
public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder())
15+
sealed_box = public.SealedBox(public_key)
16+
encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
17+
return b64encode(encrypted).decode("utf-8")
18+
19+
def main():
20+
organization = os.getenv('organization')
21+
repository_name = os.getenv('repository_name')
22+
repo_public_key = get_repository_public_key(organization=organization, repository_name=repository_name)
23+
# repo_public_key = os.environ.get("REPOSITORY_PUBLIC_KEY")
24+
# secret_value = os.environ.get("SECRET_VALUE")
25+
# public_key = "<public key here for local testing>"
26+
secret_value = "Krishnadhas"
27+
28+
if not (repo_public_key and secret_value):
29+
print("Please set REPOSITORY_PUBLIC_KEY and SECRET_VALUE environment variables.")
30+
exit(1)
31+
32+
try:
33+
encrypted_secret = encrypt(repo_public_key, secret_value)
34+
os.system(f'echo "ENCRYPTED_SECRET={encrypted_secret}" >> $GITHUB_ENV')
35+
print(f"Encrypted Secret: {encrypted_secret}")
36+
print(f"Encrypted secret added as a environment variable")
37+
return encrypted_secret
38+
except Exception as e:
39+
print(f"Error encrypting secret: {e}")
40+
exit(1)
41+
42+
if __name__ == "__main__":
43+
main()

get_repo_public_key.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import os
2+
import pytz
3+
import requests
4+
import argparse
5+
from datetime import datetime
6+
7+
def current_ist_time():
8+
"""code to return time in IST"""
9+
# Get the current time in IST
10+
ist = pytz.timezone('Asia/Kolkata')
11+
ist_now = datetime.now(ist)
12+
13+
# Format and print the current time in IST
14+
ist_now_formatted = ist_now.strftime('%Y-%m-%d %H:%M:%S %Z%z')
15+
return ist_now_formatted
16+
def get_repository_public_key(organization:str ,repository_name: str):
17+
"""
18+
Get the ORG name and repo name retrieve the public key of the repository
19+
:param organization:
20+
:param repository_name:
21+
:return:
22+
"""
23+
repository_public_key_url = f'https://api.github.com/repos/{organization}/{repository_name}/actions/secrets/public-key'
24+
headers = {
25+
"Accept": "application/vnd.github+json",
26+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
27+
"X-GitHub-Api-Version": "2022-11-28"
28+
}
29+
response = requests.get(repository_public_key_url, headers= headers)
30+
response_json = response.json()
31+
repository_public_key = response_json['key']
32+
# print(f'repo public key is {repository_public_key}')
33+
response_code = response.status_code
34+
35+
if response_code == 200:
36+
print(f'Public key for {repository_name} retrieved from {organization} Org Successfully at {current_ist_time()}')
37+
else:
38+
print(f'Failed to retrieve public key for {repository_name} retrieved from {organization} Org at {current_ist_time()}')
39+
40+
return repository_public_key
41+
42+
43+
def get_repository_public_key_id(organization:str ,repository_name: str):
44+
"""
45+
Get the ORG name and repo name retrieve the public key id of the repository
46+
:param organization:
47+
:param repository_name:
48+
:return:
49+
"""
50+
repository_public_key_id_url = f'https://api.github.com/repos/{organization}/{repository_name}/actions/secrets/public-key'
51+
headers = {
52+
"Accept": "application/vnd.github+json",
53+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
54+
"X-GitHub-Api-Version": "2022-11-28"
55+
}
56+
response = requests.get(repository_public_key_id_url, headers= headers)
57+
response_json = response.json()
58+
repository_public_key_id = response_json['key_id']
59+
# print(f'repo public key is {repository_public_key_id}')
60+
response_code = response.status_code
61+
62+
if response_code == 200:
63+
print(f'Public key id for {repository_name} retrieved from {organization} Org Successfully at {current_ist_time()}')
64+
else:
65+
print(f'Failed to retrieve public key id for {repository_name} retrieved from {organization} Org at {current_ist_time()}')
66+
67+
return repository_public_key_id
68+
69+
70+
def main():
71+
""" To test the python code """
72+
GH_TOKEN = os.environ.get("GH_TOKEN")
73+
parser = argparse.ArgumentParser(description="Get the public key of the repository in GitHub")
74+
parser.add_argument("--organization", required=True, type=str, help= "GitHub organization name")
75+
parser.add_argument("--repository_name", help= "GitHub repository name", type=str, required=True)
76+
77+
args = parser.parse_args()
78+
organization = args.organization
79+
repository_name = args.repository_name
80+
81+
try:
82+
repo_public_key = get_repository_public_key(organization, repository_name)
83+
os.system(f'echo "REPOSITORY_PUBLIC_KEY={repo_public_key}" >> $GITHUB_ENV')
84+
print(f"Public key added as a environment variable")
85+
repo_public_key_id = get_repository_public_key_id(organization, repository_name)
86+
os.system(f'echo "REPOSITORY_PUBLIC_KEY_ID={repo_public_key_id}" >> $GITHUB_ENV')
87+
print(f"Public key id added as a environment variable")
88+
89+
90+
# return encrypted_secret
91+
except Exception as e:
92+
print(f"Error retrieving public key and public key id of {repository_name}: {e}")
93+
exit(1)
94+
95+
if __name__ == "__main__":
96+
main()

0 commit comments

Comments
 (0)