coursework/ansible/Jenkinsfile
2024-11-04 19:04:39 +03:00

81 lines
3.1 KiB
Groovy

pipeline {
agent any
environment {
VAULT_PASSWORD = credentials('vault_password')
}
parameters {
choice(name: 'SITE_OPTION', choices: ['SiteA', 'SiteB', 'SiteA&B'], description: 'Select which site to deploy')
string(name: 'ADDITIONAL_CONTENT', defaultValue: 'Новое сообщение', description: 'Additional content to be included in the site')
}
stages {
stage('Decrypt SSH Key') {
steps {
script {
def tempDir = '/tmp/' + UUID.randomUUID().toString()
env.TEMP_DIR = tempDir
sh "mkdir -p ${tempDir}"
def decryptedKeyFile = "${tempDir}/id_ed25519"
def vaultPassFile = "${tempDir}/vault_pass"
writeFile file: vaultPassFile, text: VAULT_PASSWORD
sh """
ansible-vault decrypt ./ansible/id_ed25519_vault --output=${decryptedKeyFile} --vault-password-file=${vaultPassFile}
"""
def hostsFile = "${tempDir}/hosts.ini"
def hostsFileContent = """
[SiteA]
192.168.0.61 ansible_user=ansible ansible_ssh_private_key_file=${decryptedKeyFile}
[SiteB]
192.168.0.62 ansible_user=ansible ansible_ssh_private_key_file=${decryptedKeyFile}
[proxy]
192.168.0.63 ansible_user=ansible ansible_ssh_private_key_file=${decryptedKeyFile}
"""
writeFile file: hostsFile, text: hostsFileContent
env.HOSTS_FILE = hostsFile
}
}
}
stage('Deploy Site') {
steps {
script {
def sanitized_content = params.ADDITIONAL_CONTENT.replaceAll("'", "\\'").replaceAll('"', '\\"')
if (params.SITE_OPTION == 'SiteA') {
sh "export PATH=/usr/local/bin:\$PATH && ansible-playbook /ansible/playbook.yml -i ${env.HOSTS_FILE} -l SiteA -e \"additional_content='${sanitized_content}'\""
} else if (params.SITE_OPTION == 'SiteB') {
sh "export PATH=/usr/local/bin:\$PATH && ansible-playbook /ansible/playbook.yml -i ${env.HOSTS_FILE} -l SiteB -e \"additional_content='${sanitized_content}'\""
} else if (params.SITE_OPTION == 'SiteA&B') {
sh "export PATH=/usr/local/bin:\$PATH && ansible-playbook /ansible/playbook.yml -i ${env.HOSTS_FILE} -l SiteA,SiteB,proxy -e \"additional_content='${sanitized_content}'\""
}
}
}
}
}
post {
always {
script {
if (env.TEMP_DIR) {
sh "rm -rf ${env.TEMP_DIR}"
}
}
}
success {
echo 'Deployment completed successfully.'
}
failure {
echo 'Deployment failed. Please check the logs for more details.'
}
}
}