首页 > 解决方案 > 将 Ansible 主机设置为传递变量的子字符串

问题描述

我有这样的戏:

- name: Perform an action on a Runtime
  hosts: all
  roles:
  - role: mule_action_on_Runtime

调用时的变量 ( --extra-vars 'mule_runtime=MuleS01-3.7.3-Testing') 具有所需主机的前缀 ( MuleS01)。我想设置主机:MuleS01。我该怎么做呢?

标签: ansible

解决方案


鉴于您的模式始终是PartIWant-PartIDonCareAbout-AnotherPartAfterOtherDash您可以使用splitPython 的方法,然后通过 Jinja 过滤器获取列表的第一项first

这是完整的工作手册作为示例:

- hosts: local
  gather_facts: no

  tasks:
    - debug:
        msg: "{{ mule_runtime.split('-') | first }}"

这产生了回顾:

play.yml --extra-vars 'mule_runtime=MuleS01-3.7.3-Testing'


PLAY [local] *******************************************************************

TASK [debug] *******************************************************************
ok: [local] => {
    "msg": "MuleS01"
}

PLAY RECAP *********************************************************************
local                      : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


推荐阅读