Ansible:操纵变量名称

时间:2016-06-27 08:39:25

标签: variables ansible

我正在使用to_install文件中包含的变量列表(在hosts_vars下)来提供我的deploy.yml剧本。 我的hosts_vars

---
clients:
  cl1:
    to_install:
    - banana 8.1
    - Firefox 46.0.1
    to_uninstall:
    - null

我的剧本:

- name: Deploy
  hosts: win_clones
  vars_files:
    - ./hosts_vars
  tasks:
    - name: Fetching and copying the file on the client ...
      win_get_url:
        url: 'ftp://172.20.0.5/choco-repo/{{ item }}'
        dest: 'C:\Test\{{ item }}'
      with_items: "{{ clients[machine].to_install }}"
    - name: Installing the package ...
      win_chocolatey:
        name: "{{ item }}"
        state: present
        with_items: "{{ clients[machine].to_install }}"

我使用以下命令运行此游戏:

ansible-playbook deploy.yml -e machine=cl1

对于我的剧本的第一项任务,我使用win_get_url,我想将变量名称转换为:

banana8.1.nupkg
Firefox46.0.1.nupkg

对于第二个任务,我使用win_chocolatey,只传递变量的名称(没有版本号)就足够了:

banana
Firefox

我想魔法应该发生在 with_items: "{{clients[machine].to_install }}"。我怎么能在ansible中做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以使用regex_replace来执行此操作。

此:

tasks:
  - debug: msg="{{ item | regex_replace(' ', '') }}.nupkg"
    with_items: "{{ clients[machine].to_install }}"

将打印:

TASK [debug] *******************************************************************
ok: [win_clones] => (item=banana 8.1) => {
    "item": "banana 8.1", 
    "msg": "banana8.1.nupkg"
}
ok: [win_clones] => (item=Firefox 46.0.1) => {
    "item": "Firefox 46.0.1", 
    "msg": "Firefox46.0.1.nupkg"
}