如何注册with_items并根据每个项目的条件检查结果采取行动

时间:2018-12-20 10:14:04

标签: ansible

我想为两个用户注册bashrc的内容,并根据需要进行编辑。我的游戏如下。

  - name: Check bashrc
    shell: cat {{ item }}/.bashrc
    register: bashrc
    with_items:
    - "{{ nodepool_home }}"
    - "{{ zuul_home }}"

  - name: Configure bashrc
    shell:
      cmd: |
        cat >> {{ item }}/.bashrc <<EOF
        STUFF
        EOF
    with_items:
    - "{{ nodepool_home }}"
    - "{{ zuul_home }}"
    when: '"STUFF" not in bashrc.stdout'

失败如下:

fatal: [ca-o3lscizuul]: FAILED! => {"failed": true, "msg": "The conditional check '\"STUFF\" not in bashrc.stdout' failed. The error was: error while evaluating conditional (\"STUFF\" not in bashrc.stdout): Unable to look up a name or access an attribute in template string ({% if \"STUFF\" not in bashrc.stdout %} True {% else %} False {% endif %}).\nMake sure your variable name does not contain invalid characters like '-': argument of type 'StrictUndefined' is not iterable\n\nThe error appears to have been in '/root/openstack-ci/infrastructure-setup/staging/zuul/create-user.yml': line 35, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Configure bashrc\n    ^ here\n"}

1 个答案:

答案 0 :(得分:0)

我认为,如果我正确理解了您的要求,则可以使用“ lineinfile”或“ blockinfile”模块,从而省去了测试内容是否存在的麻烦:

- name: Noddy example data
  set_fact:
    single_line: "STUFF"
    multi_line: |
      STUFF
      STUFF
    profile_dirs:
      - "{{ nodepool_home }}"
      - "{{ zuul_home }}"

- name: Ensure STUFF exists in file
  lineinfile:
    path: "{{ item }}/.bashrc"
    line: "{{ single_line }}"
  loop: "{{ profile_dirs }}"

- name: Ensure block of STUFF exists in file
  blockinfile:
    path: "{{ item }}/.bashrc"
    block: "{{ multi_line }}"
  loop: "{{ profile_dirs }}"

两个模块都提供了更多控制权,您可以在这里找到其文档:lineinfile | blockinfile