Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛fix: binary download terragrunt #220

Merged
merged 1 commit into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 22 additions & 15 deletions sld-api-backend/src/worker/providers/hashicorp/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ def __init__(self, params: DownloadBinaryParams):
def get(self) -> dict:
try:
if self.iac_type == "tofu":
logging.info(f"Downloading binary iac_type {self.iac_type} version {self.version}")
iac_version = self.version.replace("v", "")
logging.info(f"Downloading binary iac_type {self.iac_type} version {iac_version}")
# Download Terraform binary if not already downloaded
if not os.path.exists(f"/tmp/{self.version}"):
os.mkdir(f"/tmp/{self.version}")
if not os.path.isfile(f"/tmp/{self.version}/tofu"):
binary = f"https://github.com/opentofu/opentofu/releases/download/v{self.version}/tofu_{self.version}_linux_amd64.zip"
binary = f"https://github.com/opentofu/opentofu/releases/download/v{iac_version}/tofu_{iac_version}_linux_amd64.zip"
print(binary)
req = requests.get(binary, verify=False)
_zipfile = zipfile.ZipFile(BytesIO(req.content))
_zipfile.extractall(f"/tmp/{self.version}")
Expand All @@ -37,12 +39,13 @@ def get(self) -> dict:
"stdout": "OpenTofu downloaded and used successfully",
}
elif self.iac_type == "terraform":
logging.info(f"Downloading binary iac_type {self.iac_type} version {self.version}")
iac_version = self.version.replace("v", "")
logging.info(f"Downloading binary iac_type {self.iac_type} version {iac_version}")
# Download Terraform binary if not already downloaded
if not os.path.exists(f"/tmp/{self.version}"):
os.mkdir(f"/tmp/{self.version}")
if not os.path.isfile(f"/tmp/{self.version}/terraform"):
binary = f"{settings.TERRAFORM_BIN_REPO}/{self.version}/terraform_{self.version}_linux_amd64.zip"
binary = f"{settings.TERRAFORM_BIN_REPO}/{iac_version}/terraform_{iac_version}_linux_amd64.zip"
req = requests.get(binary, verify=False)
_zipfile = zipfile.ZipFile(BytesIO(req.content))
_zipfile.extractall(f"/tmp/{self.version}")
Expand Down Expand Up @@ -72,17 +75,21 @@ def get(self) -> dict:
os.rename(downloaded_binary_path, renamed_binary_path)

#terrform
if not os.path.isfile(f"/tmp/{self.version}/terraform"):
binary_terraform = f"{settings.TERRAFORM_BIN_REPO}/{self.version}/terraform_1.6.5_linux_amd64.zip"
req = requests.get(binary_terraform, verify=False)
_zipfile = zipfile.ZipFile(BytesIO(req.content))
_zipfile.extractall(f"/tmp/{self.version}")
st = os.stat(f"/tmp/{self.version}/terraform")
os.chmod(f"/tmp/{self.version}/terraform", st.st_mode | stat.S_IEXEC)
current_path = os.environ.get('PATH', '')
if binary_directory not in current_path.split(os.pathsep):
updated_path = current_path + os.pathsep + binary_directory
os.environ['PATH'] = updated_path
try:
if not os.path.isfile(f"/tmp/{self.version}/terraform"):
binary_terraform = f"{settings.TERRAFORM_BIN_REPO}/1.6.5/terraform_1.6.5_linux_amd64.zip"
req = requests.get(binary_terraform, verify=False)
_zipfile = zipfile.ZipFile(BytesIO(req.content))
_zipfile.extractall(f"/tmp/{self.version}")
st = os.stat(f"/tmp/{self.version}/terraform")
os.chmod(f"/tmp/{self.version}/terraform", st.st_mode | stat.S_IEXEC)
current_path = os.environ.get('PATH', '')
if binary_directory not in current_path.split(os.pathsep):
updated_path = current_path + os.pathsep + binary_directory
os.environ['PATH'] = updated_path
except Exception as err:
logging.error(f"Failed to download Terraform binary from {binary_terraform}")
raise err

else:
logging.error(f"Failed to download Terragrunt binary from {binary_url}")
Expand Down
97 changes: 0 additions & 97 deletions sld-dashboard/app/home/deploy.py

This file was deleted.

10 changes: 4 additions & 6 deletions sld-dashboard/app/home/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,11 @@ class StackForm(FlaskForm):
validators=[validators.DataRequired()],
coerce=lambda x: 'tofu' if x == 'openTofu' else x
)
tf_version = StringField(
"IaC version",
[
validators.length(min=5, max=15, message="tf version out of reange."),
validators.DataRequired(message="tf version requerid."),
],
tf_version = SelectField(
"IaC Version",
validators=[validators.DataRequired(message="IaC version required.")]
)

project_path = StringField(
"Project_path",
[
Expand Down
66 changes: 64 additions & 2 deletions sld-dashboard/app/home/templates/stack-edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ <h3>{{stack.stack_name}}</h3>
</div>

<div class="form-group">
{{ render_field(form.iac_type, autocomplete="off", class='form-control',) }}
{{ render_field(form.iac_type, id='iacTypeSelector',autocomplete="off", class='form-control', value=stack.iac_type) }}
</div>

<div class="form-group">
{{ render_field(form.tf_version, autocomplete="off", class='form-control', value=stack.tf_version) }}
{{ render_field(form.tf_version, id='versionSelector',autocomplete="off", class='form-control', value=stack.tf_version) }}
</div>

<div class="form-group">
Expand Down Expand Up @@ -148,4 +148,66 @@ <h3>{{stack.stack_name}}</h3>
});
</script>


<script type="text/javascript">
function fetchReleaseVersions(repoUrl) {
return fetch(repoUrl)
.then(response => response.json())
.then(data => data.map(release => release.tag_name));
}

function updateVersionOptions(iacType, callback) {
let repoUrl;
switch(iacType) {
case 'terraform':
repoUrl = 'https://api.github.com/repos/hashicorp/terraform/releases';
break;
case 'terragrunt':
repoUrl = 'https://api.github.com/repos/gruntwork-io/terragrunt/releases';
break;
case 'openTofu':
repoUrl = 'https://api.github.com/repos/opentofu/opentofu/releases';
break;
default:
return;
}

fetchReleaseVersions(repoUrl).then(versions => {
const versionSelector = document.getElementById('versionSelector');
versionSelector.innerHTML = '';

versions.forEach(version => {
const option = document.createElement('option');
option.value = version;
option.text = version;
versionSelector.appendChild(option);
});

if(callback) callback();
});
}

function setInitialVersions(iacType, initialVersion) {
updateVersionOptions(iacType, function() {
const versionInput = document.getElementById('versionInput');
versionInput.value = initialVersion;
});
}

document.addEventListener('DOMContentLoaded', function () {
const iacTypeSelector = document.getElementById('iacTypeSelector');
const initialIacType = '{{ stack.iac_type }}';
const initialVersion = '{{ stack.tf_version }}';

iacTypeSelector.value = initialIacType;
setInitialVersions(initialIacType, initialVersion);

iacTypeSelector.addEventListener('mouseup', function() {
updateVersionOptions(this.value);
});
});
</script>



{% endblock javascripts %}
77 changes: 63 additions & 14 deletions sld-dashboard/app/home/templates/stacks-new.html
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,13 @@ <h1 class="h4">Add New Stack</h1>
<div class="form-group">
{{ render_field(form.squad_access, autocomplete="off", class='form-control') }}
</div>

<div class="form-group">
{{ render_field(form.iac_type, autocomplete="off", class='form-control') }}
{{ render_field(form.iac_type, id='iacTypeSelector', class='form-control') }}
</div>

<div class="form-group">
{{ render_field(form.tf_version, autocomplete="off", class='form-control', value='1.3.2') }}
{{ render_field(form.tf_version, id='versionSelector', class='form-control') }}
</div>

<div class="form-group">
{{ render_field(form.project_path, autocomplete="off", class='form-control',
placeholder='Only complete if you use monorepo') }}
Expand All @@ -73,16 +71,16 @@ <h1 class="h4">Add New Stack</h1>
<div class="form-group">
{{ render_field(form.description, autocomplete="off", class='form-control', placeholder='Description') }}
</div>
<div class="form-group">

<label for="iconSelector">Choose an Icon:</label>
<select id="iconSelector" name="icon_path" class="form-control" onchange="previewIcon()">
<!-- JavaScript will populate this -->
</select>
<div id="iconPreview" class="mt-2">
<!-- Icon preview will be displayed here -->
</div>
</div>
<div class="form-group">
<label for="iconSelector">Choose an Icon:</label>
<select id="iconSelector" name="icon_path" class="form-control" onchange="previewIcon()">
<!-- JavaScript will populate this -->
</select>
<div id="iconPreview" class="mt-2">
<!-- Icon preview will be displayed here -->
</div>
</div>

<input class="btn btn-primary" type="submit" name="stackButton" value="Create Stack">
</form>
Expand Down Expand Up @@ -142,4 +140,55 @@ <h1 class="h4">Add New Stack</h1>
};
});
</script>

<script type="text/javascript">
// Función para obtener las versiones de los releases de GitHub
function fetchReleaseVersions(repoUrl) {
return fetch(repoUrl)
.then(response => response.json())
.then(data => data.map(release => release.tag_name));
}

// Actualiza las opciones de versión de IaC basadas en el tipo de IaC seleccionado
function updateVersionOptions(iacType) {
let repoUrl;
switch(iacType) {
case 'terraform':
repoUrl = 'https://api.github.com/repos/hashicorp/terraform/releases';
break;
case 'terragrunt':
repoUrl = 'https://api.github.com/repos/gruntwork-io/terragrunt/releases';
break;
case 'openTofu':
repoUrl = 'https://api.github.com/repos/opentofu/opentofu/releases';
break;
default:
return;
}

fetchReleaseVersions(repoUrl).then(versions => {
const versionSelector = document.getElementById('versionSelector'); // Asegúrate de tener este ID en tu selector de versiones
versionSelector.innerHTML = ''; // Limpia las opciones existentes

versions.forEach(version => {
const option = document.createElement('option');
option.value = version;
option.text = version;
versionSelector.appendChild(option);
});
});
}

// Evento al cargar el documento
document.addEventListener('DOMContentLoaded', function () {
// Agrega un listener al selector de IaC Type
const iacTypeSelector = document.getElementById('iacTypeSelector'); // Asegúrate de tener este ID en tu selector de IaC Type
iacTypeSelector.addEventListener('change', function() {
updateVersionOptions(this.value);
});

// ... código existente para la selección de iconos ...
});
</script>

{% endblock javascripts %}
Loading