diff --git a/Jenkinsfile b/Jenkinsfile index e492811..6fe2cb6 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -84,6 +84,21 @@ assert r['version'] == '${IMAGE_TAG}', 'version galat!' } } } + + stage('Deploy to VM') { + steps { + withCredentials([usernamePassword(credentialsId: 'registry-creds', + usernameVariable: 'REG_USER', + passwordVariable: 'REG_PASS')]) { + sh ''' + export ANSIBLE_HOST_KEY_CHECKING=False + export IMAGE_TAG=${IMAGE_TAG} + ansible-galaxy collection install community.docker --force -q || true + ansible-playbook -i deploy/inventory.ini deploy/deploy.yml + ''' + } + } + } } post { diff --git a/deploy/deploy.yml b/deploy/deploy.yml new file mode 100644 index 0000000..cef8ee8 --- /dev/null +++ b/deploy/deploy.yml @@ -0,0 +1,70 @@ +--- +# App ko VM par deploy karo. Idempotent hai - baar baar chalao, wahi nateeja. +- name: Deploy demo-app to VM + hosts: app + gather_facts: true + + vars: + registry: "51.195.4.170:5000" + image_name: "swim/demo-app" + image_tag: "{{ lookup('env', 'IMAGE_TAG') | default('latest', true) }}" + container_name: "demo-app" + app_port: 8000 + + tasks: + - name: Registry me login + community.docker.docker_login: + registry_url: "{{ registry }}" + username: "{{ lookup('env', 'REG_USER') }}" + password: "{{ lookup('env', 'REG_PASS') }}" + no_log: true + + - name: Nayi image pull karo + community.docker.docker_image: + name: "{{ registry }}/{{ image_name }}" + tag: "{{ image_tag }}" + source: pull + force_source: true + + - name: Container chalao (purana apne aap replace hoga) + community.docker.docker_container: + name: "{{ container_name }}" + image: "{{ registry }}/{{ image_name }}:{{ image_tag }}" + state: started + restart_policy: unless-stopped + recreate: true + published_ports: + - "{{ app_port }}:8000" + env: + APP_VERSION: "{{ image_tag }}" + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request;urllib.request.urlopen('http://127.0.0.1:8000/health')"] + interval: 30s + timeout: 3s + retries: 3 + + - name: App ke healthy hone ka wait + ansible.builtin.uri: + url: "http://127.0.0.1:{{ app_port }}/health" + status_code: 200 + register: health + retries: 12 + delay: 5 + until: health.status == 200 + + - name: Deploy hui version verify karo + ansible.builtin.uri: + url: "http://127.0.0.1:{{ app_port }}/version" + return_content: true + register: ver + + - name: Nateeja dikhao + ansible.builtin.debug: + msg: "DEPLOYED -> {{ ver.json }}" + + - name: Purani images saaf karo + community.docker.docker_prune: + images: true + images_filters: + dangling: false + until: 24h diff --git a/deploy/inventory.ini b/deploy/inventory.ini new file mode 100644 index 0000000..55a50cb --- /dev/null +++ b/deploy/inventory.ini @@ -0,0 +1,7 @@ +[app] +app-vm-01 ansible_host=192.168.124.136 + +[app:vars] +ansible_user=deploy +ansible_ssh_private_key_file=/var/jenkins_secrets/deploy_key +ansible_ssh_common_args=-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null