Ansible with_items条件检查json

时间:2017-08-31 01:28:36

标签: json windows ansible jinja2 ansible-2.x

我正在尝试编写一个检查已安装的Windows功能的剧本。如果已安装,则应跳过它们,否则从我的vars列表中安装它们。

- name: win command
  win_command: 'powershell.exe "Get-WindowsFeature | Where Installed | Select -exp Name | ConvertTo-Json"'
  register: result

- name: Register vars
  set_fact:
    featureinstalled: '{{ result.stdout | from_json }}'

- name: Installing features
  win_feature:
    name: '{{ item }}'
    state: Present
  with_items:
    '{{features_to_install}}'
  when: '{{ item }} != {{ featureinstalled }}'

我的features_to_install vars位于单独的/ vars /文件中:

---
features_to_install: [FileAndStorage-Services,File-Services,.....]

如果JSON中存在该功能,我希望该剧本跳过安装该功能。我得到的错误:

  

{“失败”:是的,       “msg”:“条件检查'{{item}}!= {{featureinstalled}}'失败。错误是:模板错误,模板字符串:   预期令牌',',得到'字符串'。字符串:{%if   FileAndStorage-Services!= [u'FileAndStorage-Services',   u'Storage-Services',u'FS-SMB1',u'WoW64-Support']%} True {%else%}   False {%endif%} \ n \ n错误似乎已经出现   '/tmp/worldengine/src/roles/webserver/tasks/windows_features.yml':   第31行,第3列,但可能在文件的其他位置,具体取决于   确切的语法问题。\ n \ n违规行似乎是:\ n \ n \ n-   name:安装功能\ n ^

1 个答案:

答案 0 :(得分:0)

handy filters可用来操纵集合:

- name: Installing features
  win_feature:
    name: '{{ item }}'
    state: Present
  with_items: '{{ features_to_install | difference(featureinstalled) }}'

这将迭代features_to_install列表中的功能,但不在featureinstalled列表中。