如何在ansible playbook中动态更改主机

How to change the host dynamically in ansible playbook

我需要在 ansible playbook 中动态更改主机

下面是我的示例剧本

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

在上面的游戏中,我需要根据 DEPLOY_NAME

更改服务器

例子

如果{{DEPLOY_NAME}}=APP

然后 {{服务器}} = 172.17.65.17

如果{{DEPLOY_NAME}}=SCRIPT

然后 {{服务器}} = 172.17.65.66

之前我们将其作为 AWX 的库存传递。但现在我们需要在 playbook 上处理这个问题。

所以请帮我解决这个问题

我认为你做不到。我认为它可能对您有用,而是改为这样做:

---
- name: Deployment Playbook  
  hosts:  localhost
  tasks:
    - name: deployment   
      shell: ssh root@{{ item.server }} deploy.sh {{ item.app }}
      loop:
        - { server: 'server1', app: 'app_1' }
        - { server: 'server1', app: 'app_1' }

您甚至可以改进这一点,方法是使用 "inventory from awx",将其加载为包含此列表的 "vars_files"。因此,您的最终循环将只遍历该列表。像这样:

---
- name: Deployment Playbook  
  hosts:  localhost

  vars_files:
    - your_list_file.yml

  tasks:
    - name: deployment   
      shell: ssh root@{{ item.server }} deploy.sh {{ item.app }}
      loop: "{{ your_list_variable }}"
---
- 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'