简体   繁体   中英

Trying to pass a variable from jenkins to ansible playbook

I have setup a webhook from gitlab to kick off a jenkins job based on a tag push event. Could be a merge or commit, but the devs want to use a tag. No prob, it works fine. This job gets the hash of the tagged commit, and I've verified that also works. This job then kicks off another job which runs an ansible playbook, and starts a build.

So I am trying to pass the git commit hash as an ansible extra_var and I write the hash out to a file in the build step via execute shell command. I am using post Build Action to trigger the downstream job, and I am using the parameter from this property file.

The console output verifies this, I see the commit hash echoed out. the properties file contains:

GIT_KEY=3432134325e4323423    (fake sample hash provided)

The issue is in the downstream job, when I try and pass the GIT_KEY as an extra var so the ansible playbook will fetch the right git commit. I get the following error:

/usr/bin/git checkout --force ${GIT_KEY}", "failed": true, "msg": "Failed to checkout ${GIT_KEY}"

I've tested this statically setting the extra vars value, and it works, so I know the playbook works. Its just not interpolating this variable that I'm passing to it correctly, or as I would expect.

Does anyone know how to pass a jenkins paramter as an extra_var to ansible?

Assuming you are passing GIT_KEY like below:

ansible-playbook my_playbook.yml -e GIT_KEY=$GIT_KEY -e JENKINS_BUILD_NUMBER=$BUILD_NUMBER

In your playbook, you reference the extra vars with {{ GIT_KEY }} and {{ JENKINS_BUILD_NUMBER }}

Here is my pipeline code which I am using and passing variable to the ansible playbook.

Jenkins Pipeline

stage('Deploy to Dev Server'){
  steps{
         ansiblePlaybook credentialsId: 'Dev-Server', 
         disableHostKeyChecking: true, 
         extras: "-e DOCKER_TAG=${COMMIT_HASH} -e user=adminuser", 
         installation: 'Ansible Jenkins', 
         inventory: 'dev.inv', 
         playbook: 'deploy-ansible.yml'
     }
}

Ansible Playbook (deploy-ansible.yml)

- hosts: dev
  become: True
  tasks:
    - name: Start the container
      docker_container:
        name: backend_img
        image: "dockerhub_username/backend_img:{{COMMIT_HASH}}"
        state: started      
        published_ports:
          - 0.0.0.0:9090:9090
        env:
          ENV_MONGO_USER="{{user}}"

I couldn't get it to work with just the paramterized build plugin. But I got it to work with a workaround, I used the injectEnv plugin in the downstream job to read the KEY:Value from the file, and then I'm able to pass it as an extra var and ansible sees the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM