---
- block:
    # Handle plugins
    # If Jenkins is installed or updated, wait for pulling the Jenkins CLI, assuming 10s should be sufficiant
    - name: Wait for jenkins
      wait_for: port={{ jenkins_http_port }} delay={{ jenkins_restart_delay }}
      when: jenkins_has_been_restarted is changed or jenkins_has_been_started is changed

    # Create Jenkins CLI destination directory
    - name: "Create Jenkins CLI destination directory"
      file: path={{ jenkins_dest }} state=directory

    - name: Get Jenkins CLI
      get_url: url={{ jenkins_local_url}}/jnlpJars/jenkins-cli.jar dest={{ jenkins_cli_dest }} mode=0440

    # Create the Jenkins administrative user password file
    - name: Create the Jenkins administrative user password file
      copy: content={{ jenkins_admin_pwd }} dest={{ jenkins_admin_user_pwd_file }} mode=600

    - name: Install plugins without a specific version
      jenkins_plugin: name="{{ item.name }}" state={{ item.state | default('latest') }} with_dependencies={{ item.dependencies | default(True) }} url={{ jenkins_local_url }} url_username={{ jenkins_access_params.url_username }} url_password={{ jenkins_access_params.url_password }} 
      when: item.version is not defined
      with_items: '{{ jenkins_plugins }}'
      notify: Restart jenkins

    - name: Install plugins with a specific version
      jenkins_plugin: name="{{ item.name }}" state={{ item.state | default('latest') }} version='{{ item.version }}' url={{ jenkins_local_url }} url_username={{ jenkins_access_params.url_username }} url_password={{ jenkins_access_params.url_password }} 
      when: item.version is defined
      with_items: '{{ jenkins_plugins }}'
      notify: Restart jenkins

  become: True
  become_user: '{{ jenkins_username }}'
  when: jenkins_install
  tags: [ 'jenkins', 'jenkins_plugins', 'jenkins_master' ]