Skip to content

Commit db3ce33

Browse files
An action to set the Terraform Envrionment variables to access Azure
1 parent c3535a1 commit db3ce33

File tree

7 files changed

+206
-2
lines changed

7 files changed

+206
-2
lines changed

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ ipython_config.py
105105
# This is especially recommended for binary packages to ensure reproducibility, and is more
106106
# commonly ignored for libraries.
107107
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108-
#poetry.lock
108+
poetry.lock
109109
#poetry.toml
110110

111111
# pdm
@@ -173,7 +173,7 @@ cython_debug/
173173
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174174
# and can be added to the global gitignore or merged into this file. For a more nuclear
175175
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
176-
#.idea/
176+
.idea/
177177

178178
# Abstra
179179
# Abstra is an AI-powered process automation framework.

action.yaml

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
name: 'Terraform Azure Authentication Action '
3+
description: 'An action to set the Terraform Envrionment variables to access Azure'
4+
author: 'githubofkrishnadhas'
5+
# reference https://haya14busa.github.io/github-action-brandings/
6+
branding:
7+
icon: 'cloud-lightning'
8+
color: 'green'
9+
10+
runs:
11+
using: 'composite'
12+
steps:
13+
14+
- name: Checkout
15+
uses: actions/checkout@v4
16+
with:
17+
repository: 'devwithkrishna/terraform-azure-authentication-action'
18+
19+
- name: list files
20+
shell: bash
21+
run: |
22+
echo "Listing files in the current directory:"
23+
ls -la
24+
25+
- name: Install Python
26+
uses: actions/setup-python@v5
27+
with:
28+
python-version: '3.11'
29+
30+
- name: package installations
31+
shell: bash
32+
run: |
33+
pip install poetry
34+
poetry install -v --no-root --no-interaction
35+
36+
- name: Run Python program
37+
shell: bash
38+
run: |
39+
poetry run python3 fetch_kv_secret.py

config.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[keyvault]
2+
name = "ARCHITECTS-KEYVAULT"
3+
4+
[secrets]
5+
ARM_TENANT_ID="ARM-TENANT-ID"
6+
ARM_CLIENT_ID="withtf-id"
7+
ARM_CLIENT_SECRET="withtf-password"

fetch_kv_secret.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import os
2+
import logging
3+
import toml
4+
from azure.identity import DefaultAzureCredential
5+
from azure.keyvault.secrets import SecretClient
6+
from dotenv import load_dotenv
7+
from setup_logging import setup_logging
8+
9+
10+
def fetch_kv_secret():
11+
"""
12+
Fetches secrets from an Azure Key Vault and sets them as environment variables.
13+
14+
This function reads the Key Vault name and secret names from a `config.toml` file,
15+
retrieves the secrets from the Key Vault using Azure SDK, and stores them in the
16+
environment variables for further use.
17+
18+
Raises:
19+
KeyError: If the `config.toml` file does not contain the required keys.
20+
azure.core.exceptions.HttpResponseError: If there is an issue with the Azure Key Vault request.
21+
"""
22+
# Initialize a logger for logging information and errors
23+
logger = logging.getLogger(__name__)
24+
25+
# Authenticate using the default Azure credential chain
26+
credential = DefaultAzureCredential()
27+
28+
# Load configuration from the `config.toml` file
29+
config = toml.load("config.toml")
30+
31+
# Retrieve the Key Vault name from the configuration
32+
keyvault = keyvault_name = config["keyvault"]["name"]
33+
34+
# Construct the Key Vault URL
35+
vault_url = f"https://{keyvault_name}.vault.azure.net/"
36+
37+
# Retrieve the secret names from the configuration
38+
secret_names = config["secrets"]
39+
40+
# Create a SecretClient to interact with the Azure Key Vault
41+
client = SecretClient(vault_url=vault_url, credential=credential)
42+
43+
# Dictionary to store the retrieved secrets
44+
secrets = {}
45+
46+
# Iterate over the secret names and fetch their values from the Key Vault
47+
for key, secret in secret_names.items():
48+
secret_name = secret
49+
# Retrieve the secret value from the Key Vault
50+
get_secret = client.get_secret(secret_name)
51+
# Store the secret value in the dictionary
52+
secrets[key] = get_secret.value
53+
# Set the secret value as an environment variable
54+
os.environ[key] = get_secret.value
55+
56+
57+
def main():
58+
"""
59+
Main function to fetch a secret from Azure Key Vault.
60+
"""
61+
load_dotenv()
62+
setup_logging()
63+
logger = logging.getLogger(__name__)
64+
logger.info("Starting to fetch secrets from Azure Key Vault")
65+
fetch_kv_secret()
66+
logger.info("Finished fetching secrets from Azure Key Vault")
67+
68+
if __name__ == "__main__":
69+
main()

logging-conf.yaml

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
version: 1
2+
formatters:
3+
simple:
4+
format: '%(asctime)s - %(msecs)03d - %(name)s - %(levelname)s - %(message)s'
5+
datefmt: '%Y-%m-%dT%H:%M:%S'
6+
ts_format:
7+
format: '%(asctime)s - %(msecs)03d+00:00 - %(name)s - %(levelname)s [%(name)s] [%(process)d] %(message)s'
8+
datefmt: '%Y-%m-%dT%H:%M:%S'
9+
handlers:
10+
console:
11+
class: logging.StreamHandler
12+
formatter: simple
13+
level: INFO
14+
stream: ext://sys.stdout
15+
logfile:
16+
class: logging.FileHandler
17+
formatter: simple
18+
level: INFO
19+
filename: env-setup.log
20+
mode: w
21+
22+
loggers:
23+
__main__:
24+
level: DEBUG
25+
handlers: [console, logfile]
26+
propagate: no
27+
azure:
28+
level: WARNING
29+
handlers: [console, logfile]
30+
propagate: no
31+
azure.core.pipeline.policies.http_logging_policy:
32+
level: WARNING
33+
handlers: [ console, logfile ]
34+
propagate: no
35+
azure.identity._credentials.chained:
36+
level: WARNING
37+
handlers: [ console, logfile ]
38+
propagate: no
39+
root:
40+
level: DEBUG
41+
handlers: [console, logfile]

pyproject.toml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[tool.poetry]
2+
name = "terraform-azure-authentication-action"
3+
version = "0.1.0"
4+
description = "An action to set the Terraform Envrionment variables to access Azure"
5+
authors = ["githubofkrishnadhas <[email protected]>"]
6+
readme = "README.md"
7+
8+
[tool.poetry.dependencies]
9+
python = "^3.11"
10+
python-dotenv = "^1.0.0"
11+
azure-identity = "^1.12.0"
12+
azure-keyvault-secrets = "^4.7.0"
13+
toml = "^0.10.2"
14+
pyyaml = "^6.0.1"
15+
16+
[build-system]
17+
requires = ["poetry-core"]
18+
build-backend = "poetry.core.masonry.api"

setup_logging.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import logging
2+
import logging.config
3+
import os
4+
import yaml
5+
from dotenv import load_dotenv
6+
7+
8+
def setup_logging(default_path='logging-conf.yaml', default_level: int=logging.INFO,
9+
env_key='LOGGING_CONFIG'):
10+
"""
11+
Setup logging configuration
12+
:param default_path: path to the logging configuration file
13+
:param default_level: default logging level
14+
:param env_key: environment variable key for the logging configuration file path
15+
:param log_in_utc: whether to log in UTC
16+
"""
17+
load_dotenv()
18+
path = default_path
19+
value = os.getenv(env_key, None)
20+
if value:
21+
path = value
22+
23+
if os.path.exists(path):
24+
with open(path, 'r') as f:
25+
config = yaml.safe_load(f.read())
26+
logging.config.dictConfig(config)
27+
else:
28+
logging.basicConfig(level=default_level)
29+
30+
return None

0 commit comments

Comments
 (0)