Search code examples
ansibledevopsansible-2.xansible-awx

How to change the host dynamically in ansible playbook


I need to change the host dynamically in ansible playbook

Below is my sample playbook

---
- name: Deployment Playbook  
  hosts:  “{{Servers}}”
  tasks:
    - name: deployment   
      shell: "deploy.sh {{DEPLOY_NAME}}"  

In above play I need to change the server with respect of DEPLOY_NAME

Example

If {{DEPLOY_NAME}}=APP

THEN {{Servers}} = 172.17.65.17

If {{DEPLOY_NAME}}=SCRIPT

THEN {{Servers}} = 172.17.65.66

Previously we passed this as inventory from AWX. But now we need to handle this on playbook.

So please help me on this issue


Solution

  • ---
    - name: Deployment Playbook targetting Servers_1, will be skipped if DEPLOY_NAME is not APP
      hosts:  “{{Servers_1}}”
      tasks:
        - name: deployment   
          shell: "deploy.sh {{DEPLOY_NAME}}"
          when: DEPLOY_NAME == 'APP'
    
    - name: Deployment Playbook targetting Servers_1, will be skipped if DEPLOY_NAME is not SCRIPT      
      hosts:  “{{Servers_2}}”
      tasks:
        - name: deployment   
          shell: "deploy.sh {{DEPLOY_NAME}}"
          when: DEPLOY_NAME == 'SCRIPT'