Skip to content

Instantly share code, notes, and snippets.

@crossan007
Last active August 26, 2021 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crossan007/6fce653a12500eaf70ad36c360637e1e to your computer and use it in GitHub Desktop.
Save crossan007/6fce653a12500eaf70ad36c360637e1e to your computer and use it in GitHub Desktop.
Ansible Download Jenkins Artifact from API by Partial Filename Query

Defaults

#Jenkins Query Params
JenkinsBaseURL: "https://jenkins.yourco.com"
JenkinsJobName: "<YOUR JOB NAME>"
JenkinsMultibranchPipelineBranchName: "master"
JenkinsBuildQuery: "(builds[?artifacts[?contains(fileName, '{{ArtifactDesiredVersion}}') == `true`]])[0]" # Partial artifact file name - this assumes your file names are unique per build
JenkinsBuild: "{{ (jenkins.content | from_json) | json_query(JenkinsBuildQuery) }}"
JenkinsBuildArtifactsURL: "{{JenkinsBuild.url}}artifact/"
BuildsDownloaded: false
ArtifactQuery: "(artifacts[?contains(fileName, 'zip') == `true`])[0].fileName"
ArtifactFileName: "{{ (JenkinsBuild) | to_json | from_json | json_query(ArtifactQuery) }}"
ArtifactRemotePath: "{{JenkinsBuildArtifactsURL}}/{{ArtifactFileName}}"
ArtifactLocalPath: "{{BuildTempDirectory}}\\{{ArtifactFileName}}"
BuildTempDirectory: "C:\\deploy"
jenkins_usernane: "jenkins"
jenkins_password: "jenkins"

Tasks


- name: Find selected Build
  win_uri:
    url: "{{JenkinsBaseURL}}/job/{{JenkinsJobName}}/job/{{JenkinsMultibranchPipelineBranchName}}/api/json?depth=2"
    force_basic_auth: yes
    user: '{{jenkins_username}}'
    password: '{{jenkins_password}}'
    return_content: yes
  register: jenkins

- name: print URLs
  debug:
    msg:
      - "{{ArtifactRemotePath}}"

- name: Create temporary build directory
  win_file:
    state: directory
    path: "{{BuildTempDirectory}}"

- name: Stage Application Files from Jenkins
  win_get_url:
    url: "{{buildToDeploy.RemotePath}}"
    force: no
    force_basic_auth: yes
    url_username: '{{jenkins_username}}'
    url_password: '{{jenkins_password}}'
    dest: "{{buildToDeploy.LocalPath}}"
  register: downloaded
  loop: 
    - RemotePath: "{{ArtifactRemotePath}}"
      LocalPath: "{{ArtifactLocalPath}}"
  loop_control:
    loop_var: buildToDeploy

@mahespth
Copy link

This was very useful but I found that jenkins returned sparse data that could cause issues dependent on the version of ansible/jmsepath. To this I include builds[?description != None && contains(description,'{{ searchstr }}') ...... otherwise JMSE would throw errors depending on the quality of the jenkins job data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment