Skip to content

Commit 8e3faaf

Browse files
DEVOPS-49 added workflow encryptionand creating secret
1 parent 08cc9a8 commit 8e3faaf

File tree

5 files changed

+247
-1
lines changed

5 files changed

+247
-1
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
name: create_or_update_repository_secrets
2+
on:
3+
workflow_dispatch:
4+
inputs:
5+
organization:
6+
required: true
7+
description: 'GitHub Organization name'
8+
type: string
9+
repository_name:
10+
required: true
11+
description: 'GitHub repository on which secret need to be created'
12+
type: string
13+
secret_name:
14+
required: true
15+
description: 'Repository Secret name'
16+
type: string
17+
secret_value:
18+
required: true
19+
description: 'secret content'
20+
21+
run-name: ${{ github.actor }} creting or updating ${{ inputs.secret_name }} in ${{ inputs.repository_name }}
22+
jobs:
23+
create_or_update_repository_secrets:
24+
runs-on: ubuntu-latest
25+
steps:
26+
steps:
27+
- name: git checkout
28+
uses: actions/checkout@v4
29+
- name: Set up Python
30+
uses: actions/setup-python@v2
31+
with:
32+
python-version: '3.11'
33+
- name: package installations
34+
run: |
35+
pip install pipenv
36+
pipenv install
37+
- name: get public key
38+
id: get-public-key
39+
env:
40+
GH_TOKEN: ${{ secrets.DEVWITHKRISHNA_PERSONAL_ACCESS_TOKEN }}
41+
run: |
42+
pipenv run python3 get_repository_public_key --organization ${{ inputs.organization }} \
43+
--repository_name ${{ inputs.repository_name }}
44+
- name: Encrypt secret
45+
id: encrypt-secret
46+
env:
47+
REPOSITORY_PUBLIC_KEY: ${{ env.REPOSITORY_PUBLIC_KEY }}
48+
SECRET_VALUE: ${{ inputs.secret_value }}
49+
run: |
50+
pipenv run python3 encrypt_using_libnacl.py
51+
- name: create or update repository secret
52+
env:
53+
organization: ${{ inputs.organization }}
54+
secret_name: ${{ inputs.secret_name }}
55+
ENCRYPTED_SECRET: ${{ env.ENCRYPTED_SECRET }}
56+
REPOSITORY_PUBLIC_KEY_ID: ${{ env.REPOSITORY_PUBLIC_KEY_ID }}
57+
GH_TOKEN: ${{ secrets.DEVWITHKRISHNA_PERSONAL_ACCESS_TOKEN }}
58+
run: |
59+
pipenv run python3 create_or_update_repo_secret.py
60+
- name: Completed
61+
run: |
62+
echo "program completed successfully"
63+

Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ name = "pypi"
77
argparse = "=1.4.0"
88
requests = "=2.31.0"
99
pytz = "=2024.1"
10+
PyNaCl = "=1.5.0"
1011

1112
[requires]
1213
python_version = "3"

Pipfile.lock

Lines changed: 82 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

create_or_update_repo_secret.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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_organization_secret_github(organization: str, secret_name: str):
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 = os.getenv('ENCRYPTED_SECRET')
25+
if not encrypted_secret:
26+
print("ENCRYPTED_SECRET environment variable is not set or is empty.")
27+
print(f'encrypted sec is: {encrypted_secret}')
28+
ist_now_formatted = current_ist_time()
29+
github_org_secret_endpoint = f"https://api.github.com/orgs/{organization}/actions/secrets/{secret_name}"
30+
31+
headers = {
32+
"Accept": "application/vnd.github+json",
33+
"Authorization": f"Bearer {os.getenv('GH_TOKEN')}",
34+
"X-GitHub-Api-Version": "2022-11-28"
35+
}
36+
data = {
37+
"encrypted_value": encrypted_secret,
38+
"visibility": "all",
39+
"key_id": os.getenv('PUBLIC_KEY_ID')
40+
}
41+
response = requests.put(github_org_secret_endpoint, headers=headers, json=data)
42+
if response.status_code == '201':
43+
print(f"Secret {secret_name} created {organization} at {ist_now_formatted}")
44+
else:
45+
print(f"Secret {secret_name} updated on {organization} at {ist_now_formatted}")
46+
47+
48+
def main():
49+
"""To test the code"""
50+
# Configuring to read ENCRYPTED_SECRET
51+
# encrypted_secret = os.getenv('ENCRYPTED_SECRET')
52+
# organization = 'devwithkrishna'
53+
# secret_name = 'noidea'
54+
organization = os.getenv('organization')
55+
secret_name = os.getenv('secret_name')
56+
57+
# Function call
58+
create_or_update_organization_secret_github(organization, secret_name)
59+
60+
if __name__ == "__main__":
61+
main()

encrypt_using_libnacl.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
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+
public_key = os.environ.get("PUBLIC_KEY")
21+
secret_value = os.environ.get("SECRET_VALUE")
22+
# public_key = "<public key here for local testing>"
23+
# secret_value = "Krishnadhas"
24+
25+
if not (public_key and secret_value):
26+
print("Please set PUBLIC_KEY and SECRET_VALUE environment variables.")
27+
exit(1)
28+
29+
try:
30+
encrypted_secret = encrypt(public_key, secret_value)
31+
os.system(f'echo "ENCRYPTED_SECRET={encrypted_secret}" >> $GITHUB_ENV')
32+
print(f"Encrypted Secret: {encrypted_secret}")
33+
print(f"Encrypted secret added as a environment variable")
34+
return encrypted_secret
35+
except Exception as e:
36+
print(f"Error encrypting secret: {e}")
37+
exit(1)
38+
39+
if __name__ == "__main__":
40+
main()

0 commit comments

Comments
 (0)