我遇到了同样的问题。就我而言,我的部分变量在字典中,即 with_dict 变量(循环),我必须在每个 item.key 上运行 3 个命令。当您必须使用 with_dict 字典来运行多个命令时,此解决方案更为相关(不需要 with_items)
在一项任务中使用 with_dict 和 with_items 没有帮助,因为它没有解析变量。
我的任务是这样的:
- name: Make install git source
command: "{{ item }}"
with_items:
- cd {{ tools_dir }}/{{ item.value.artifact_dir }}
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} all
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} install
with_dict: "{{ git_versions }}"
roles/git/defaults/main.yml 是:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
对于每个 {{ item }} (对于上面提到的 3 个命令),上述导致类似于以下的错误。如您所见,tools_dir 的值未填充(tools_dir 是一个在通用角色的 defaults/main.yml 中定义的变量,并且 item.value.git_tar_dir 的值未填充/解析)。
failed: [server01.poc.jenkins] => (item=cd {# tools_dir #}/{# item.value.git_tar_dir #}) => {"cmd": "cd '{#' tools_dir '#}/{#' item.value.git_tar_dir '#}'", "failed": true, "item": "cd {# tools_dir #}/{# item.value.git_tar_dir #}", "rc": 2}
msg: [Errno 2] No such file or directory
解决方案很简单。我没有在 Ansible 中使用“COMMAND”模块,而是使用“Shell”模块并在角色/git/defaults/main.yml 中创建了一个变量
所以,现在角色/git/defaults/main.yml 看起来像:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} all && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} install"
#or use this if you want git installation to work in ~/tools/git-x.x.x
git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix=`pwd` all && make prefix=`pwd` install"
#or use this if you want git installation to use the default prefix during make
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make all && make install"
任务 roles/git/tasks/main.yml 看起来像:
- name: Make install from git source
shell: "{{ git_pre_requisites_install_cmds }}"
become_user: "{{ build_user }}"
with_dict: "{{ git_versions }}"
tags:
- koba
这一次,值被成功替换,因为模块是“SHELL”,并且 ansible 输出回显了正确的值。 这不需要 with_items: 循环。
"cmd": "cd ~/tools/git-2.6.3 && make prefix=/home/giga/tools/git-2.6.3 all && make prefix=/home/giga/tools/git-2.6.3 install",