Настройка ansible.cfg в работе Jenkins - PullRequest
0 голосов
/ 26 сентября 2019

На самом деле я работаю над созданием заданий по развертыванию программного обеспечения, которые будут развертывать мое программное обеспечение через роли Ansible.Роли Ansible будут выполняться на центральном сервере Jenkins, чтобы иметь графический интерфейс для «всех», которые должны иметь возможность выполнять развертывание программного обеспечения.

Мои роли Ansible, книги и т. Д. Имеют свой собственный ansible.cfg, которыйотличается от стандартной конфигурации ansible в /etc/ansible/ansible.cfg, также /etc/ansible/ansible.cfg не будет изменен, поскольку будет использоваться другими Ansible Tasks, которым требуются другие параметры.

ТеперьЯ ищу способ указать путь к файлу ansible.cfg в задании Jenkins.Я уже нашел документ Ansible (https://docs.ansible.com/ansible/latest/reference_appendices/config.html#ansible-configuration-settings), но я не могу установить ANSIBLE_CONFIG в задании Jenkins, а также я не знаю "дом" задания Jenkins.

У кого-нибудь была такая же проблема, и есть ли какое-то решение для этого? Может быть, установив env vars в Jenkins Job?

EDIT: я также пробовал использовать EnvInject Plugin в Jenkins, чтобы установить ANSIBLE_CONFIG для запуска сборки.К сожалению, здесь нет решения. Я попробовал его двумя способами, которые описаны здесь: Как установить переменные среды в Jenkins?

Это мой вывод в Jenkins (тоже пробовалбез "" для пути):

Running as SYSTEM
[EnvInject] - Loading node environment variables.
Building in workspace /var/lib/jenkins/workspace/prepare-app-deploy-set-hostgroups
using credential app-deploy-qit-ssh-key
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url git@op-scm.sys.fintechgroup.com:jenkins-ansible-deployments/non-docker-deployment.git # timeout=10
Fetching upstream changes from git@op-scm.sys.fintechgroup.com:jenkins-ansible-deployments/non-docker-deployment.git
 > git --version # timeout=10
using GIT_SSH to set credentials app-deploy-qit SSH Key
 > git fetch --tags --progress git@op-scm.sys.fintechgroup.com:jenkins-ansible-deployments/non-docker-deployment.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/qit^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/qit^{commit} # timeout=10
Checking out Revision 8bfcc1186338670f2e16c60e1f274d399d44c2a2 (refs/remotes/origin/qit)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 8bfcc1186338670f2e16c60e1f274d399d44c2a2
Commit message: "envinject-api und envinject für Jenkins Qit"
 > git rev-list --no-walk c49903a669f19bf04451d9fc933e791e59bd50b5 # timeout=10
[EnvInject] - Executing scripts and injecting environment variables after the SCM step.
[EnvInject] - Injecting as environment variables the properties content 
ANSIBLE_CONFIG="/opt/ansible/non-docker-deployment/ansible.cfg"

[EnvInject] - Variables injected successfully.
[prepare-app-deploy-set-hostgroups] $ /bin/sh -xe /tmp/jenkins4170164383320983136.sh
+ echo '"/opt/ansible/non-docker-deployment/ansible.cfg"'
"/opt/ansible/non-docker-deployment/ansible.cfg"
[prepare-app-deploy-set-hostgroups] $ ansible-playbook /opt/ansible/non-docker-deployment/playbooks/prepare-app-deploy-serial.yml -i /opt/ansible/non-docker-deployment/hosts_qit -f 5 --vault-password-file /var/lib/jenkins/workspace/prepare-app-deploy-set-hostgroups/vault5523069360317322241.password -e @/opt/ansible/non-docker-deployment/vaults/app-deploy-qit.yml -e host=banksystem_ha2_all_qit -e {'javainstall':false,'wildflyinstall':false,'perlinstall':false,'updateos':false,'rebootserver':false}
ERROR! the role 'prepare-app-deploy' was not found in /opt/ansible/non-docker-deployment/playbooks/roles:/root/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles:/opt/ansible/non-docker-deployment/playbooks

The error appears to be in '/opt/ansible/non-docker-deployment/playbooks/prepare-app-deploy-serial.yml': line 5, column 9, but may
be elsewhere in the file depending on the exact syntax problem.

Справочная информация об ошибке со стороны Ansible: мои роли сохраняются в другом каталоге, который установлен в отдельном ansible.cfg. Как Ansible не может найтироли, которые я знаю, что ansible.cfg не загружен правильно.

EDITEDIT: Здесь экспорт моего проекта frestyle в формате xml:

<?xml version='1.1' encoding='UTF-8'?>
<project>
  <actions/>
  <description>prepare-app-deploy over ansible on qit instances and set hostgroups by yourself</description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <com.cwctravel.hudson.plugins.extended__choice__parameter.ExtendedChoiceParameterDefinition plugin="extended-choice-parameter@0.78">
          <name>Hostgruppen</name>
          <description>Hier die Hostgruppen aus dem Ansible inventory auswählen, die vorbereitet werden sollen</description>
          <quoteValue>false</quoteValue>
          <saveJSONParameterToFile>false</saveJSONParameterToFile>
          <visibleItemCount>10</visibleItemCount>
          <type>PT_RADIO</type>
          <value>host1,host2,host3,host4,host5</value>
          <multiSelectDelimiter>,</multiSelectDelimiter>
          <projectName>prepare-app-deploy-set-hostgroups</projectName>
        </com.cwctravel.hudson.plugins.extended__choice__parameter.ExtendedChoiceParameterDefinition>
        <hudson.model.BooleanParameterDefinition>
          <name>javainstall</name>
          <description>Soll Java installiert werden?</description>
          <defaultValue>false</defaultValue>
        </hudson.model.BooleanParameterDefinition>
        <hudson.model.BooleanParameterDefinition>
          <name>wildflyinstall</name>
          <description>Soll Wildfly installiert werden? - nur für Linuxsysteme</description>
          <defaultValue>false</defaultValue>
        </hudson.model.BooleanParameterDefinition>
        <hudson.model.BooleanParameterDefinition>
          <name>perlinstall</name>
          <description>Soll Perl installiert werden?</description>
          <defaultValue>false</defaultValue>
        </hudson.model.BooleanParameterDefinition>
        <hudson.model.BooleanParameterDefinition>
          <name>updateos</name>
          <description>Sollen OS Updates durchgeführt werden? Schließt einen evtl. Reboot des Servers mit ein!</description>
          <defaultValue>false</defaultValue>
        </hudson.model.BooleanParameterDefinition>
        <hudson.model.BooleanParameterDefinition>
          <name>rebootserver</name>
          <description>Soll der Server durchgebootet werden?</description>
          <defaultValue>false</defaultValue>
        </hudson.model.BooleanParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
    <hudson.plugins.disk__usage.DiskUsageProperty plugin="disk-usage@0.28"/>
    <com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty plugin="gitlab-plugin@1.5.12">
      <gitLabConnection></gitLabConnection>
    </com.dabsquared.gitlabjenkins.connection.GitLabConnectionProperty>
    <hudson.plugins.jira.JiraProjectProperty plugin="jira@3.0.9"/>
  </properties>
  <scm class="hudson.plugins.git.GitSCM" plugin="git@3.12.0">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <url>git@op-scm.sys.fintechgroup.com:jenkins-ansible-deployments/non-docker-deployment.git</url>
        <credentialsId>app-deploy-qit-ssh-key</credentialsId>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>*/qit</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
    <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
    <submoduleCfg class="list"/>
    <extensions>
      <hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
        <relativeTargetDir>/opt/ansible/non-docker-deployment</relativeTargetDir>
      </hudson.plugins.git.extensions.impl.RelativeTargetDirectory>
    </extensions>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>ln -sf /opt/ansible/non-docker-deployment/ansible.cfg ${PWD}/ansible.cfg</command>
    </hudson.tasks.Shell>
    <org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder plugin="ansible@1.0">
      <playbook>/opt/ansible/non-docker-deployment/playbooks/prepare-app-deploy-serial.yml</playbook>
      <inventory class="org.jenkinsci.plugins.ansible.InventoryPath">
        <path>/opt/ansible/non-docker-deployment/hosts_qit</path>
      </inventory>
      <limit></limit>
      <tags></tags>
      <skippedTags></skippedTags>
      <startAtTask></startAtTask>
      <credentialsId></credentialsId>
      <vaultCredentialsId>app-deploy-qit-ansible-vault</vaultCredentialsId>
      <become>false</become>
      <becomeUser></becomeUser>
      <sudo>false</sudo>
      <sudoUser></sudoUser>
      <forks>5</forks>
      <unbufferedOutput>true</unbufferedOutput>
      <colorizedOutput>false</colorizedOutput>
      <disableHostKeyChecking>true</disableHostKeyChecking>
      <additionalParameters>-e @/opt/ansible/non-docker-deployment/vaults/app-deploy-qit.yml -e host=$Hostgruppen -e &quot;{&apos;javainstall&apos;:$javainstall,&apos;wildflyinstall&apos;:$wildflyinstall,&apos;perlinstall&apos;:$perlinstall,&apos;updateos&apos;:$updateos,&apos;rebootserver&apos;:$rebootserver}&quot;</additionalParameters>
      <copyCredentialsInWorkspace>false</copyCredentialsInWorkspace>
    </org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder>
  </builders>
  <publishers>
    <hudson.tasks.Mailer plugin="mailer@1.24">
      <recipients>david.pasternak@flatex.com mando.ahnert@flatex.com christian.baron@flatex.com markus.frahm@flatex.com tobias.koenigs@flatex.com</recipients>
      <dontNotifyEveryUnstableBuild>true</dontNotifyEveryUnstableBuild>
      <sendToIndividuals>false</sendToIndividuals>
    </hudson.tasks.Mailer>
  </publishers>
  <buildWrappers/>
</project>

Я также попробовал его на Groovyскрипт для крена конвейере.К сожалению, с тем же результатом.

pipeline {
  agent any

  parameters {
    extendedChoice description: 'Hier die Hostgruppen aus dem Ansible inventory auswählen, die vorbereitet werden sollen', multiSelectDelimiter: ',', name: 'Hostgruppen', quoteValue: false, saveJSONParameterToFile: false, type: 'PT_RADIO', value: 'appdeploy_servers_qit,banksystem_ha1_lx_qit,banksystem_ha1_win_qit,banksystem_ha1_all_qit,banksystem_ha2_lx_qit,banksystem_ha2_win_qit,banksystem_ha2_all_qit,banksystem_ha2_ungerade_qit,banksystem_ha2_gerade_qit,BaZe_biw_qit,BaZe_kat_qit,BaZe_pbb_qit,BaZe_vdh_qit,calcserv_data_blz2_qit,calcserv_data_ibanplus_qit,calcserv_data_rocs_qit,WebFiliale2_banking_pbb_qit,WebFiliale2_banking_pbb_btz_qit,WebFiliale2_biw_qit,WebFiliale2_biw_auxmoney_qit,WebFiliale2_biwzv_bds_qit,WebFiliale2_biwzv_fcc_qit,WebFiliale2_biwzv_xs2a_qit,WebFiliale2_crosslend_qit,WebFiliale2_flatex_de_qit,WebFiliale2_flatex_de_cfd_login_qit,WebFiliale2_flatex_de_wpinfo_qit,WebFiliale2_flatexbanking_de_qit,WebFiliale2_flatexbanking_de_wpinfo_qit,WebFiliale2_flatex_at_cfd_login_qit,WebFiliale2_flatexbanking_at_qit,WebFiliale2_flatexbanking_at_wpinfo_qit,WebFiliale2_flatexbanking_nl_qit,WebFiliale2_flatexbanking_nl_cfd_login_qit,WebFiliale2_flatexbanking_nl_wpinfo_qit,WebFiliale2_kat_at_qit,WebFiliale2_kat_de_qit,WebFiliale2_vitrade_qit,WebFiliale2_vitrade_cfd_login_qit,WebFiliale2_banking_vitrade_qit', visibleItemCount: 10
    booleanParam defaultValue: false, description: 'Soll Java installiert werden?', name: 'javainstall'
    booleanParam defaultValue: false, description: 'Soll Wildfly installiert werden? - nur für Linuxsysteme', name: 'wildflyinstall'
    booleanParam defaultValue: false, description: 'Soll Perl installiert werden?', name: 'perlinstall'
    booleanParam defaultValue: false, description: 'Sollen OS Updates durchgeführt werden? Schließt einen evtl. Reboot des Servers mit ein!', name: 'updateos'
    booleanParam defaultValue: false, description: 'Soll der Server durchgebootet werden?', name: 'rebootserver'
  }

  stages {
    stage('Parameter testen') {
      steps {
        echo "Hostgruppen: $params.Hostgruppen"
        echo "Java installieren?: $params.javainstall"
        echo "Wildfly installieren?: $params.wildflyinstall"
        echo "Perl installieren?: $params.perlinstall"
        echo "Updates installieren?: $params.updateos"
        echo "Server rebooten?: $params.rebootserver"
      }
    }

    stage ('Git Projekt auschecken') {
      steps {
        checkout([$class: 'GitSCM', branches: [[name: '*/qit']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: '/opt/ansible/non-docker-deployment']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'app-deploy-qit-ssh-key', url: 'git@op-scm.sys.fintechgroup.com:jenkins-ansible-deployments/non-docker-deployment.git']]])
      }
    }

    stage ('Ansible Playbook ausführen') {
      environment {
        ANSIBLE_CONFIG = "/opt/ansible/non-docker-deployment/ansible.cfg"
        ANSIBLE_INVENTORY = "/opt/ansible/non-docker-deployment/hosts_qit"
        ANSIBLE_PB = "/opt/ansible/non-docker-deployment/playbooks/prepare-app-deploy-serial.yml"
        ANSIBLE_VAULT = "/opt/ansible/non-docker-deployment/vaults/app-deploy-qit.yml"
      }
      steps {
        sh label: '', script: 'export ANSIBLE_CONFIG=$ANSIBLE_CONFIG'
        ansiblePlaybook disableHostKeyChecking: true, extras: '-e @$ANSIBLE_VAULT -e host=$params.Hostgruppen -e \"{\'javainstall\':$params.javainstall,\'wildflyinstall\':$params.wildflyinstall,\'perlinstall\':$params.perlinstall,\'updateos\':$params.updateos,\'rebootserver\':$params.rebootserver}\"', inventory: '$ANSIBLE_INVENTORY', playbook: '$ANSIBLE_PB', vaultCredentialsId: 'app-deploy-qit-ansible-vault'
      }
    }
  }
}

Кто-нибудь, кто мог бы помочь?

Спасибо и всего наилучшего, Дэвид

1 Ответ

0 голосов
/ 26 сентября 2019

По выводу похоже, что вы используете команду shell для запуска ansible-playbook.Вы можете попробовать установить переменную окружения перед командой ansible-playbook.Ниже приведен пример.

$ env ANSIBLE_CONFIG=/opt/ansible/non-docker-deployment/ansible.cfg ansible-playbook /opt/ansible/non-docker-deployment/playbooks/prepare-app-deploy-serial.yml -i /opt/ansible/non-docker-deployment/hosts_qit -f 5 --vault-password-file /var/lib/jenkins/workspace/prepare-app-deploy-set-hostgroups/vault5523069360317322241.password -e @/opt/ansible/non-docker-deployment/vaults/app-deploy-qit.yml -e host=banksystem_ha2_all_qit -e {'javainstall':false,'wildflyinstall':false,'perlinstall':false,'updateos':false,'rebootserver':false}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...