ansible - 如何注册_items并根据每个项目的条件检查结果采取行动
问题描述
我想为两个用户注册 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"}
解决方案
我认为,如果我正确理解您的要求,您可以使用“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 | 块文件
推荐阅读
- angular - 权限被拒绝 AngularCLI 安装无法从远程存储库中读取
- angular - ionic 5 - 在现有项目中创建选项卡
- java - Normalize Text - 编写加密和解密文本的方法
- python - 如何计算只有一个输出单元的梯度?
- c++ - 朋友方法作为常量
- python - 训练 StyleGan 时出现 CUDNN_STATUS_NOT_INITIALIZED 错误
- javascript - Ionic 4:离子芯片默认可激活/可点击;如何关闭?
- javascript - 您可以使用字符串模板文字将整个对象作为字符串返回吗?
- redirect - 将不同的 Web 服务合并到一个端口
- ssl - SSL 错误“在链中找不到预期的服务器名称。”