ansible switch语句实现

有时候,需要使用switch语句,可是ansible 没有switch语句,我结合set_fact实现了类似的功能。
直接上代码:

---

- hosts: "{{ hosts_group }}"
  remote_user: root
  vars:
    hosts_group: "localhost"

  tasks:
    - set_fact:
        env_name: 'china'
      when: env_name_alias=='zhonguo'

    - set_fact:
        env_name: 'china'
      when: env_name_alias=='cn'

    - set_fact:
        env_name: "{{ env_name_alias }}"
      when: env_name_alias not in ['zhonguo','cn']
    
    - debug:
        msg: "env_name is {{ env_name }}"
    
    - debug:
        msg: "env_name_alias is {{ env_name_alias }}"

看下执行结果:

[root@iZj6cj20vqe3q7vt49zoxdZ ansible-best-practice]# ansible-playbook ansible-set_fact.yml -e "env_name_alias=cn"
 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'


PLAY [localhost] **************************************************************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************************************************************
ok: [localhost]

TASK [set_fact] ***************************************************************************************************************************************************
skipping: [localhost]

TASK [set_fact] ***************************************************************************************************************************************************
ok: [localhost]

TASK [set_fact] ***************************************************************************************************************************************************
skipping: [localhost]

TASK [debug] ******************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "env_name is china"
}

TASK [debug] ******************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "env_name_alias is cn"
}

PLAY RECAP ********************************************************************************************************************************************************
localhost                  : ok=4    changed=0    unreachable=0    failed=0

[root@iZj6cj20vqe3q7vt49zoxdZ ansible-best-practice]#

你可能感兴趣的:(ansible)