---
- name: "Configure Docker server(s)"
  hosts: "all"
  become: yes
  become_method: sudo

  vars:
    
    cert_template_dir: /etc/ssl/templates
    ca_config_json: /etc/ssl/templates/ca-config.json
    ca_csr_json: /etc/ssl/templates/ca-csr.json
    ca_server_cfssl_temp: /tmp/ca_server
    ca_server_key: /etc/ssl/private/ca_server.key
    ca_server_cert: /etc/ssl/certs/ca_server.pem
    ca_server_csr: /etc/ssl/certs/ca_server.csr
    ldap_server_cfssl_temp: /tmp/ldap_server
    ldap_server_key: /etc/ssl/private/ldap_server.key
    ldap_server_cert: /etc/ssl/certs/ldap_server.pem
    ldap_server_csr: /etc/ssl/certs/ldap_server.csr
    ldap_server_dhparams: /etc/ssl/certs/ldap_server_dhparam.pem
    ldap_client_cert: /etc/ldap/ca_certs.pem
    ldap_config_admin: cn=admin,cn=config

    aswf_ldap_domain: "dc={{ aswf_domain | regex_replace('\\.', ',dc=') }}"

    docker_users: ["{{ ansible_user }}"]
    avahi__alias_enabled: True
    
    jenkins_version: lts
    jenkins_url: http://127.0.0.1
    jenkins_port: 8080
    jenkins_install_via: "docker"
#    jenkins_java_opts: -Djenkins.install.runSetupWizard=false -Djavax.net.ssl.trustStore=/var/jenkins_home/.keystore/cacerts -Djavax.net.ssl.trustStorePassword=changeit
#    jenkins_java_opts: -Djenkins.install.runSetupWizard=false 
    jenkins_config_owner: "jenkins"
    jenkins_config_group: "jenkins"
    jenkins_home: /var/jenkins_home
    jenkins_docker_image: jenkins/jenkins
    jenkins_docker_container_name: aswf_jenkins
    jenkins_docker_expose_port: false
    jenkins_source_dir_configs: "{{ playbook_dir }}/jenkins-configs"
    jenkins_source_config_xml: "{{ jenkins_source_dir_configs }}/config_pre_plugins.xml"
    jenkins_include_custom_files: true
    jenkins_include_secrets: true
    jenkins_custom_files:
      - src:  "hudson.plugins.git.GitSCM.xml"
        dest: "hudson.plugins.git.GitSCM.xml"
      - src:  "jenkins.model.JenkinsLocationConfiguration.xml"
        dest: "jenkins.model.JenkinsLocationConfiguration.xml"
      - src:  "jenkins.plugins.msginject.MsgInjectConfig.xml"
        dest: "jenkins.plugins.msginject.MsgInjectConfig.xml"
      - src:  "envinject-plugin-configuration.xml"
        dest: "envinject-plugin-configuration.xml"
      - src:  "jenkins.CLI.xml"
        dest: "jenkins.CLI.xml"
      - src:  "jenkins.model.DownloadSettings.xml"
        dest: "jenkins.model.DownloadSettings.xml"
      - src:  "jenkins.security.QueueItemAuthenticatorConfiguration.xml"
        dest: "jenkins.security.QueueItemAuthenticatorConfiguration.xml"
      - src:  "jenkins.security.UpdateSiteWarningsConfiguration.xml"
        dest: "jenkins.security.UpdateSiteWarningsConfiguration.xml"
      - src:  "jenkins.security.apitoken.ApiTokenPropertyConfiguration.xml"
        dest: "jenkins.security.apitoken.ApiTokenPropertyConfiguration.xml"
      - src:  "gerrit-trigger.xml"
        dest: "gerrit-trigger.xml"
      - src:  "hudson.model.UpdateCenter.xml"
        dest: "hudson.model.UpdateCenter.xml"
      - src:  "hudson.plugins.git.GitTool.xml"
        dest: "hudson.plugins.git.GitTool.xml"
      - src:  "nodeMonitors.xml"
        dest: "nodeMonitors.xml"
      - src:  "org.jenkinsci.plugins.ghprb.GhprbTrigger.xml"
        dest: "org.jenkinsci.plugins.ghprb.GhprbTrigger.xml"

    jenkins_plugins:
      - jdk-tool
      - command-launcher
      - antisamy-markup-formatter
      - build-timeout
      - config-file-provider
      - description-setter
      - envinject
      - extended-read-permission
      - git
      - postbuildscript
      - ssh-agent
      - ws-cleanup
      - gerrit-trigger
      - github
      - ghprb
      - mask-passwords
      - msginject
      - openstack-cloud
      - timestamper
      - matrix-auth
      - matrix-project
      - ldap
      - workflow-api

  roles:
    - role: debops.avahi
      tags: role::avahi
 
  tasks:
  - name: Update and upgrade apt packages
    apt:
      upgrade: yes
      update_cache: yes

  - name: install packages to build python-ldap, manage certificates and run OpenLDAP
    apt:
      name: "{{ packages }}"
    vars:
      packages:
        - libldap2-dev
        - libsasl2-dev
        - gnutls-bin
        - ssl-cert
        - golang-cfssl
        - slapd
        - ldap-utils
        - openjdk-8-jre-headless

  - name: install required pip packages
    include_role:
      name: geerlingguy.pip
    vars:
      pip_install_packages:
        - name: docker
        - name: python-ldap

  - name: install make sure pip3 is installed
    include_role:
      name: geerlingguy.pip
    vars:
      pip_package: python3-pip

  - name: install required pip3 packages
    # Somehow can't get geerlingguy.pip role to install both python2 and python3 packages, call pip role directly
    pip:
      name: jenkins-utils
      executable: pip3

  - name: slapd debconf questions
    # These values are taken from the osixia/openldap container
    debconf:
      name:     slapd
      question: "{{ item.question }}"
      value:    "{{ item.value }}"
      vtype:    "{{ item.vtype }}"
    loop:
      - { question: 'slapd/internal/generated_adminpw', value: '{{ ansible_ssh_pass }}',     vtype: 'password' }
      - { question: 'slapd/internal/adminpw',           value: '{{ ansible_ssh_pass }}',     vtype: 'password' }
      - { question: 'slapd/password2',                  value: '{{ ansible_ssh_pass }}',     vtype: 'password' }
      - { question: 'slapd/password1',                  value: '{{ ansible_ssh_pass }}',     vtype: 'password' }
      - { question: 'slapd/dump_database_destdir',      value: '/var/backups/slapd-VERSION', vtype: 'string'   }
      - { question: 'slapd/domain',                     value: '{{ aswf_domain }}',          vtype: 'string'   }
      - { question: 'shared/organization',              value: 'ASWF Clone',                 vtype: 'string'   }
      - { question: 'slapd/backend',                    value: 'MDB',                        vtype: 'string'   }
      - { question: 'slapd/purge_database',             value: 'true',                       vtype: 'boolean'  }
      - { question: 'slapd/move_old_database',          value: 'true',                       vtype: 'boolean'  }
      - { question: 'slapd/allow_ldap_v2',              value: 'false',                      vtype: 'boolean'  }
      - { question: 'slapd/no_configuration',           value: 'false',                      vtype: 'boolean'  }
      - { question: 'slapd/dump_database',              value: 'when needed',                vtype: 'select'   }

  - name: reconfigure slapd
    # There's an outstanding Ansible PR for a reconfigure option to debconf module but as of Oct 2018 it hasn't gone in yet
    # https://github.com/ansible/ansible/pull/39794
    command: dpkg-reconfigure -f noninteractive slapd

  - name: simple authentication for cn=config LDAP database
    # By default debconf only sets up -Y EXTERNAL SASL authentication for cn=config LDAP database
    # Add simple authentication as per:
    # https://ubuntuforums.org/showthread.php?t=1515119
    # FIXME: need to crypt and encode the password, follow instructions at:
    # https://www.digitalocean.com/community/tutorials/how-to-change-account-passwords-on-an-openldap-server
    ldap_attr:
      # Don't set bind_dn, rely on default -Y EXTERNAL SASL authentication
      dn: olcDatabase={0}config,cn=config
      name: "{{ item.name }}"
      values: "{{ item.val }}"
      state: exact
    loop:
      - { name: olcRootDN, val: "{{ ldap_config_admin }}" }
      - { name: olcRootPW, val: "{{ ansible_ssh_pass }}" }

  - name: create cert template dir
    file:
      path: "{{ cert_template_dir }}"
      state: directory
      owner: root
      group: root
      mode: 0755
      
  - name: copy cfssl certificate config
    copy:
      src: ca-config.json
      dest: "{{ ca_config_json }}"

  - name: copy cfssl certificate request
    template:
      src: ca-csr-json.j2
      dest: "{{ ca_csr_json }}"

  - name: Are we missing any of the ssl related files
    stat:
      path: "{{ item }}"
    register: cert_stat
    loop: 
      - "{{ ca_server_key }}"
      - "{{ ca_server_cert }}"
      - "{{ ca_server_csr }}"
      - "{{ ldap_server_key }}"
      - "{{ ldap_server_cert }}"
      - "{{ ldap_server_csr }}"

  - name: Any one missing file and we regenerate them all
    # Likely there's a better way to do this
    set_fact:
      regen_certs: (cert_stat.results[0].stat.exists == False) or
                   (cert_stat.results[1].stat.exists == False) or
                   (cert_stat.results[2].stat.exists == False) or
                   (cert_stat.results[3].stat.exists == False) or
                   (cert_stat.results[4].stat.exists == False) or
                   (cert_stat.results[5].stat.exists == False) 

  - name: generate self signed CA private key and cert
    shell: cfssl gencert -initca "{{ ca_csr_json }}" | cfssljson -bare "{{ ca_server_cfssl_temp }}"
    when: regen_certs

  - name: generate LDAP server private key and cert
    shell: cfssl gencert -ca "{{ ca_server_cfssl_temp }}.pem" -ca-key "{{ ca_server_cfssl_temp }}-key.pem" -config "{{ ca_config_json }}" 
             -hostname dev."{{ aswf_domain }}",ldap."{{ aswf_domain }}"  "{{ ca_csr_json }}" |
             cfssljson -bare "{{ ldap_server_cfssl_temp }}"
    when: regen_certs

  - name: copy CA server private key
    copy:
      src: "{{ ca_server_cfssl_temp }}-key.pem"
      dest: "{{ ca_server_key }}"
      mode: 0640
      group: ssl-cert
      remote_src: yes
      force: yes
    when: regen_certs

  - name: copy CA self signed certificate
    copy:
      src: "{{ ca_server_cfssl_temp }}.pem"
      dest: "{{ ca_server_cert }}"
      remote_src: yes
      force: yes
    when: regen_certs

  - name: copy CA CSR
    copy:
      src: "{{ ca_server_cfssl_temp }}.csr"
      dest: "{{ ca_server_csr }}"
      remote_src: yes
      force: yes
    when: regen_certs

  - name: copy LDAP server private key
    copy:
      src: "{{ ldap_server_cfssl_temp }}-key.pem"
      dest: "{{ ldap_server_key }}"
      mode: 0640
      group: ssl-cert
      remote_src: yes
      force: yes
    when: regen_certs

  - name: copy LDAP self signed certificate
    copy:
      src: "{{ ldap_server_cfssl_temp }}.pem"
      dest: "{{ ldap_server_cert }}"
      remote_src: yes
      force: yes
    when: regen_certs

  - name: copy LDAP CSR
    copy:
      src: "{{ ldap_server_cfssl_temp }}.csr"
      dest: "{{ ldap_server_csr }}"
      remote_src: yes
      force: yes
    when: regen_certs

  - name: delete intermediate files
    file:
      path: "{{ item }}"
      state: absent
    loop:
      - "{{ ca_server_cfssl_temp }}-key.pem"
      - "{{ ca_server_cfssl_temp }}.pem"
      - "{{ ca_server_cfssl_temp }}.csr"
      - "{{ ldap_server_cfssl_temp }}-key.pem"
      - "{{ ldap_server_cfssl_temp }}.pem"
      - "{{ ldap_server_cfssl_temp }}.csr"
    when: regen_certs

  - name: generate LDAP server dhparam file
    # Diffie-Hellman parameter file for key exchange to ensure forward secrecy
    # Equivalent GnuTLS command is:
    # certtool --generate-dh-params --outfile dhparam_file.pem --bits 2048
    command: openssl dhparam -out "{{ ldap_server_dhparams }}" 2048
    args:
      creates: "{{ ldap_server_dhparams }}"

  - name: add openldap group
    # this shouldn't happen, but we need to make sure LDAP private key is readable in weird cases where LDAP server
    # is already partially configured to look for it and won't start if it's not accessible. So we need to make sure
    # we have openldap user and group
    group:
      name: openldap
      system: yes
  
  - name: add openldap user
    # And now make sure that openldap group is part of ssl-cert group
    user:
      name: openldap
      system: yes
      home: /var/lib/ldap
      shell: /in/false
      group: openldap
      groups: ssl-cert
      comment: "OpenLDAP Server Account"
      password_lock: yes

  - name: LDAP cert accessible for LDAP clients
    copy:
      src: "{{ ca_server_cert }}"
      dest: "{{ ldap_client_cert }}"
      remote_src: yes

  - name: LDAP clients pick up correct CA cert
    # /etc/ldap/ldap.conf comes from libldap-common package
    lineinfile:
      path: /etc/ldap/ldap.conf
      regexp: '^TLS_CACERT\s+(/etc/ssl/certs/ca-certificates.crt|{{ ldap_client_cert }})$'
      line:   'TLS_CACERT {{ ldap_client_cert }}'

  - name: LDAP clients respect TLS certificate errors
    lineinfile:
      path: /etc/ldap/ldap.conf
      regexp: '^TLS_REQCERT\s+(never|allow|try|demand|hard)$'
      line:   'TLS_REQCERT demand'

  - name: restart slapd
    service:
      name: slapd
      state: restarted

  - name: Configure TLS private key (ignore errors)
    # Workaround for slapd wanting TLS properties set at same time
    # see https://github.com/ansible/ansible/issues/25665
    ldap_attr:
      bind_dn: "{{ ldap_config_admin }}"
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: cn=config
      name: olcTLSCertificateKeyFile
      values: "{{ ldap_server_key }}"
      state: exact
    failed_when: False

  - name: Configure slapd TLS parameters
    ldap_attr:
      bind_dn: "{{ ldap_config_admin }}"
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: cn=config
      name: "{{ item.name }}"
      values: "{{ item.path }}"
      state: exact
    loop:
      - { name: olcTLSCertificateFile,    path: "{{ ldap_server_cert }}" }
      - { name: olcTLSCertificateKeyFile, path: "{{ ldap_server_key }}" }
      - { name: olcTLSCACertificateFile,  path: "{{ ca_server_cert }}" }
      - { name: olcTLSDHParamFile,        path: "{{ ldap_server_dhparams }}" }

  - name: Configure TLS only access to slapd
    # Once this is done we can no longer edit LDAP database without specifying start_tls: yes
    ldap_attr:
      bind_dn: "{{ ldap_config_admin }}"
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: olcDatabase={1}mdb,cn=config
      name: olcSecurity
      values: "tls=1"
      state: exact

  - name: SHA-1 hashed password for LDAP users
    shell: /usr/sbin/slappasswd -s "{{ ansible_ssh_pass }}"
    register: hashed_user_ldap_passwd

  - name: explicit bind user entry for LDAP
    # FIXME: what should its password be? Can set it with:
    # ldappasswd -H ldapi:/// -x -D cn=admin,{{ aswf_ldap_domain }} -w LDAP_ROOT_PW -Z -S "cn=binduser,{{ aswf_ldap_domain }}"
    # FIXME: should this user live in the users OU? Should it derive from organizationalPerson
    # FIXME: can this exist only as an LDAP account? Jenkins seems to be happy with that
    # FIXME: should all our LDAP accounts derive from the same set of base objectClasses ?
    ldap_entry:
      bind_dn: cn=admin,{{ aswf_ldap_domain }}
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: cn=binduser,{{ aswf_ldap_domain }}
      objectClass:
        - top
        - posixAccount
        - shadowAccount
        - inetOrgPerson
      attributes:
        cn: binduser
        uid: binduser
        uidNumber: 2000
        gidNumber: 200
        homeDirectory: /home/binduser
        loginShell: /bin/bash
        gecos: suser
        displayName: LDAP Bind Account
        sn: Bind
        userPassword: "{{ hashed_user_ldap_passwd.stdout }}"
        shadowLastChange: -1
        shadowMax: -1
        shadowWarning: -1
      state: present
      start_tls: yes

  - name: disallow anonymous binding to LDAP
    ldap_attr:
      bind_dn: "{{ ldap_config_admin }}"
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: cn=config
      name: olcDisallows
      values: bind_anon
      state: exact
      start_tls: yes

  - name: disable anonymous access to LDAP frontend
    ldap_attr:
      bind_dn: "{{ ldap_config_admin }}"
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: olcDatabase={-1}frontend,cn=config
      name: olcRequires
      values: authc
      state: exact
      start_tls: yes

  - name: enable LDAPS
    lineinfile:
      path: /etc/default/slapd
      regexp: '^SLAPD_SERVICES="ldap:/// (ldaps:/// |)ldapi:///"$'
      line:   'SLAPD_SERVICES="ldap:/// ldaps:/// ldapi:///"'

  - name: restart slapd
    service:
      name: slapd
      state: restarted

  - name: create OU for users
    ldap_entry:
      bind_dn: cn=admin,{{ aswf_ldap_domain }}
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: ou=users,{{ aswf_ldap_domain }}
      objectClass: organizationalUnit
      attributes:
        ou: users
        description: all users
      state: present
      start_tls: yes

  - name: create OU for groups
    ldap_entry:
      bind_dn: cn=admin,{{ aswf_ldap_domain }}
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: ou=groups,{{ aswf_ldap_domain }}
      objectClass: organizationalUnit
      attributes:
        ou: groups
        description: all users
      state: present
      start_tls: yes

  - name: install and configure Docker
    include_role:
      name: geerlingguy.docker

  #
  # The following is a failed experiment at enabling the Docker API to allow Ansible
  # to run inside containers on the remote host. See the commented out calls lower 
  # to add the Jenkins container to the inventory and to use delegate_to to run
  # a specific module inside that container.
  #

 #- name: enable Docker API create systemd override directory
 #   file:
 #     path: /etc/systemd/system/docker.service.d
 #     state: directory

 # - name: enable Docker API created systemd override file
 #   copy:
 #     src: docker_override.conf
 #     dest: /etc/systemd/system/docker.service.d/override.conf

 # - name: enable Docker API restart daemon
 #   systemd:
 #     state: restarted
 #     daemon_reload: yes
 #     name: docker

  - name: add CNAME avahi aliases
    # Can't use blockinfile, no comments in avahi aliases
    lineinfile:
      path: /etc/avahi/aliases
      line: '{{ item }}'
    loop:
      - 'jenkins.local'
      - 'nexus.local'
      - 'nexus3.local'
      - 'sonar.local'
      - 'logs.local'
      - 'ldap.local'

  - name: restart avahi-alias service
    # avahi-alias service doesn't support reload
    service:
      name:  avahi-alias
      state: restarted 

  - name: add NGINX proxy container
    docker_container:
      name: aswf_nginx
      image: jwilder/nginx-proxy
      published_ports:
        - 80:80
      restart_policy: unless-stopped
      volumes: /var/run/docker.sock:/tmp/docker.sock:ro

  - name: create jenkins user and group
    # For now assume the jenkins account is just a system account that doesn't need a password for logins,
    # uncomment the "password" parameter to give it a password
    user:
      name: jenkins
      comment: Jenkins User
      home: /var/jenkins_home
      shell: /bin/bash
      # password: "{{ ansible_ssh_pass | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}"
    register: jenkins_user_result

  - name: create jobbuilder user and group
    # FIXME: This possibly only needed inside LDAP user database?
    user:
      name: jobbuilder
      comment: Jenkins Job Builder
      home: /home/jobbuilder
      shell: /bin/bash
      password: "{{ ansible_ssh_pass | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}"
    register: jobbuilder_user_result

  - name: create jobbuilder LDAP user
    # FIXME: what should its password be? Can set it with:
    # ldappasswd -H ldapi:/// -x -D cn=admin,{{ aswf_ldap_domain }} -w LDAP_ROOT_PW -Z -S "cn=jobbuilder,{{ aswf_ldap_domain }}"
    # FIXME: what should we be using for email addresses?
    ldap_entry:
      bind_dn: cn=admin,{{ aswf_ldap_domain }}
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: cn=jobbuilder,ou=users,{{ aswf_ldap_domain }}
      objectClass:
        - top
        - posixAccount
        - shadowAccount
        - inetOrgPerson
      attributes:
        cn: jobbuilder
        uid: jobbuilder
        uidNumber: "{{ jobbuilder_user_result.uid }}"
        gidNumber: "{{ jobbuilder_user_result.uid }}"
        homeDirectory: /home/jobbuilder
        loginShell: /bin/bash
        gecos: Job Builder
        displayName: Job Builder
        sn: Builder
        mail: jobbuider@{{ aswf_domain }}
        userPassword: "{{ hashed_user_ldap_passwd.stdout }}"
        shadowLastChange: -1
        shadowMax: -1
        shadowWarning: -1
      state: present
      start_tls: yes

  - name: create jobbuilder LDAP group
    ldap_entry:
      bind_dn: cn=admin,{{ aswf_ldap_domain }}
      bind_pw: "{{ ansible_ssh_pass }}"
      dn: cn=jobbuilder,ou=groups,{{ aswf_ldap_domain }}
      objectClass:
        - top
        - posixGroup
      attributes:
        cn: jobbuilder
        description: Job Builder Group
        memberUid: jobbuilder
        gidNumber: "{{ jobbuilder_user_result.uid }}"
      state: present
      start_tls: yes

  - name: add Jenkins container
    include_role:
      name: emmetog.jenkins

# - name: add Jenkins container to inventory
#    add_host:
#      name: "{{ jenkins_docker_container_name }}"
#      ansible_connection: docker
#      ansible_docker_extra_args: "-H=tcp://dev.{{ aswf_domain }}:2376"
#      ansible_user: jenkins
#    changed_when: false

  - name: create Java keystore location for Jenkins container
    file:
      path: "{{ jenkins_home }}/.keystore"
      state: directory

  - name: copy default Java keystore into Jenkins container
    copy:
      src: /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
      dest: "{{ jenkins_home }}/.keystore/"
      remote_src: yes

  - name: copy self-signed CA cert into Jenkins container
    copy:
      src: "{{ ca_server_cert }}"
      dest: "{{ jenkins_home }}/.keystore/"
      remote_src: yes

  - name: Add self signed CA cert to Jenkins Java keystore
    # FIXME: too many hardcoded paths
    # Can't seem to make it work inside the container
    # delegate_to: "{{ jenkins_docker_container_name }}"
    java_cert:
      keystore_path: "{{ jenkins_home }}/.keystore/cacerts"
      cert_path: "{{ jenkins_home }}/.keystore/ca_server.pem"
      cert_alias: ldap.{{ aswf_domain }}636
      keystore_pass: changeit
      keystore_create: yes
      state: present

  - name: stop Jenkins container
    docker_container:
      name: "{{ jenkins_docker_container_name }}"
      state: stopped

  - name: recopy Jenkins config that depends on plugins being present
    template:
      src: "{{ jenkins_source_dir_configs }}/config.xml.j2"
      dest: "{{ jenkins_home }}/config.xml"
      owner: jenkins
      group: jenkins
      mode: 0644

  - name: restart Jenkins container as vhost with host entries
    # FIXME: hard coded my domain name
    docker_container:
      name: "{{ jenkins_docker_container_name }}"
      hostname: jenkins.{{ aswf_domain }}
      image: jenkins/jenkins:lts
      exposed_ports:
        - 8080
        - 50000
      restart_policy: unless-stopped
      volumes: 
        - "{{ jenkins_home }}:{{ jenkins_home }}"
        - /etc/ldap:/etc/ldap
      env:
        # JAVA_OPTS: "{{ jenkins_java_opts }}"
        # If we try to set these globally it will mess up first attempt at starting container
        JAVA_OPTS: -Djenkins.install.runSetupWizard=false -Djavax.net.ssl.trustStore=/var/jenkins_home/.keystore/cacerts -Djavax.net.ssl.trustStorePassword=changeit
        VIRTUAL_HOST: jenkins.{{ aswf_domain }}
        VIRTUAL_PORT: 8080
      etc_hosts:
        jenkins.panisset.io: 172.17.0.1
        sonar.panisset.io:   172.17.0.1
        nexus.panisset.io:   172.17.0.1
        logs.panisset.io:    172.17.0.1
        nexus3.panisset.io:  172.17.0.1
        dev.panisset.io:  172.17.0.1
        ldap.panisset.io: 172.17.0.1

  - name: wait for Jenkins hudson secret to be generated
    wait_for:
      path: "{{ jenkins_home }}/secrets/hudson.util.Secret"

  - name: stop Jenkins container again
    docker_container:
      name: "{{ jenkins_docker_container_name }}"
      state: stopped

  - name: encrypt Jenkins LDAP user password
    script: jenkins_password_crypt.py "{{ ansible_ssh_pass }}"
    args:
      executable: python3
    register: jenkins_encrypt_out

  - name: capture encrypted Jenkins LDAP user password debug
    set_fact:
      manager_password_secret: "{{ jenkins_encrypt_out.stdout | trim }}"

  - name: add LDAP user password to Jenkins config
    lineinfile:
      path: "{{ jenkins_home }}/config.xml"
      regexp: '^\s*<managerPasswordSecret>.*</managerPasswordSecret>$'
      line:   '        <managerPasswordSecret>{{ manager_password_secret }}</managerPasswordSecret>'

  - name: start Jenkins container for good with password binduser password
    docker_container:
      name: "{{ jenkins_docker_container_name }}"
      state: started

  - name: add Nexus2 container
    docker_container:
     name: aswf_nexus
     hostname: nexus.{{ aswf_domain }}
     image: sonatype/nexus
     exposed_ports:
       - 8081
     restart_policy: unless-stopped
     env:
       VIRTUAL_HOST: nexus.{{ aswf_domain }}
       VIRTUAL_PORT: 8081

  - name: add Nexus3 container
    docker_container:
      name: aswf_nexus3
      hostname: nexus3.{{ aswf_domain }}
      image: sonatype/nexus3
      exposed_ports:
        - 8081
      restart_policy: unless-stopped
      env:
        VIRTUAL_HOST: nexus3.{{ aswf_domain }}
        VIRTUAL_PORT: 8081

#  - name: add SonarQube container
#    docker_container:
#        name: aswf_sonar
#        hostname: sonar.{{ aswf_domain }}
#        image: sonarqube
#        exposed_ports:
#          - 9000
#          - 9092
#        restart_policy: unless-stopped
#        env:
#          VIRTUAL_HOST: sonar.{{ aswf_domain }}
#          VIRTUAL_PORT: 9000
#          SONARQUBE_JDBC_USERNAME: sonar
#          SONARQUBE_JDBC_PASSWORD: sonar
#          SONARQUBE_JDBC_URL: jdbc:postgresql://localhost/sonar

