Ansible playbook dynamically set variable according to the conditions
First, a new inventory, a list of hosts are as follows:
node-01 ansible_host=192.168.64.30 node-02 ansible_host=192.168.64.31 [app] node-01 [db] node-02
Then create a test.yml, add the following:
- hosts: db[0]:app[0] # 支持索引取值 vars: - Role: "{{ 'db' if 'app' in group_names else 'app' }}" # 动态设置变量 - Ports: app: 4503 db: 4502 pre_tasks: # 默认tasks只能在roles执行完后才执行,而pre-tasks可以在roles之前执行 - name: Debug debug: msg: This is a test message. roles: - testrole
新建 roles/testrole/defaults/main.yml
--- RESTLink: 'http://{{ inventory_hostname }}:{{ Ports[Role] }}'
新建 roles/testrole/tasks/main.yml
--- - debug: msg: "Final URL is {{ RESTLink }}"
The playbook execution
ansible-playbook -i inventory test.yml
The output is:
PLAY [db[0]:app[0]] ******************************************************************************************************************************************* TASK [Gathering Facts] **************************************************************************************************************************************** Tuesday 27 August 2019 18:22:30 +0800 (0:00:00.121) 0:00:00.121 ******** ok: [node-01] ok: [node-02] TASK [debug] ************************************************************************************************************************************************** Tuesday 27 August 2019 18:22:32 +0800 (0:00:02.242) 0:00:02.363 ******** ok: [node-02] => { "msg": "This is a test message." } ok: [node-01] => { "msg": "This is a test message." } TASK [testrole : Debug] *************************************************************************************************************************************** Tuesday 27 August 2019 18:22:33 +0800 (0:00:00.255) 0:00:02.620 ******** ok: [node-02] => { "msg": "Final URL is http://node-02:4503" } ok: [node-01] => { "msg": "Final URL is http://node-01:4502" } PLAY RECAP **************************************************************************************************************************************************** node-01 : ok=3 changed=0 unreachable=0 failed=0 node-02 : ok=3 changed=0 unreachable=0 failed=0
to sum up:
1. When used in this manner, the order of execution for your playbook is as follows:
- Any
pre_tasks
defined in the play. - Any handlers triggered so far will be run.
- Each role listed in
roles
will execute in turn. Any role dependencies defined in the rolesmeta/main.yml
will be run first, subject to tag filtering and conditionals. - Any
tasks
defined in the play. - Any handlers triggered so far will be run.
- Any
post_tasks
defined in the play. - Any handlers triggered so far will be run.