ansible - 使用多个配置变量验证行
问题描述
我正在学习 ansible 并且无法用简单的术语用 asnible 来解决这个问题。
我有一个文件,其中包含:
net.ifnames=0 dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=LABEL=writable rootfstype=ext4 elevator=deadline rootwait fixrtc cgroup_memory=1 cgroup_enable=memory
这是一行,例如,我想检查 cgroup_memory 是否设置为 1,如果未设置为 1,以及是否缺少整个设置,请将其附加到行尾。
我知道如何用 bash 和 sed 来做这件事的非常简单的方法,但是我不能用 ansible “正确”的方式来解决问题,而不使用 lineinfile 并替换整行......正如提到的 lineinfile 正在使用整行这样我认为这并不理想.. 我研究的下一个模块是替换它可能会起作用,但我不能只寻找“cgroup_memory=1”,因为它会查看“cgroup_memory=0”并评估为那不是“cgroup_memory= 1”,我最终在一个文件中得到 cgroup_memory=1 cgroup_memory=0 ......不知何故,我需要提取值,比较并替换该值(保持整行完好无损),如果它不存在附加到末尾线...
这是我想要的 bash 版本: https ://pastebin.com/1TCz30Nq
这是我最接近我需要的地方:
- name: "Check for cgroup_memory"
shell: grep -v '^[[:space:]]*#' /tmp/cmdline.txt_old | grep -icP "cgroup_memory=-?\d+[[:space:]]" || true
register: grep_value
changed_when: False
- debug:
var: grep_value
- name: "Variable Missing: Add cgroup_memory=1 to end of line"
become: true
replace: dest=/tmp/cmdline.txt_old regexp='(\s+)$' replace=' cgroup_memory=1'
when: grep_value.stdout == "0"
- name: "Variable Exist: Set cgroup_memory=1"
become: true
replace: dest=/tmp/cmdline.txt_old regexp='cgroup_memory=\d+' replace='cgroup_memory=1'
when: grep_value.stdout == "1"
这不会忽略 # 行,因此替换会很高兴地更改评论中的值,这是不好的。这也没有评估价值,但我想我可以在确定它在那里之后进行 grep 和拆分。我不想抱怨,但我认为 ansible 是配置管理的完美选择,也是我做的第一件简单的事情很多通过shell脚本并不是那么简单......(如果我不想使用shell模块)
解决方案
确保cgroup_memory
将其设置为 1 的一种方法是使用 Ansible替换模块。replace 模块可以匹配 aregexp
并将其替换为我们想要的。
例子:
tasks:
- name: set cgroup_memory to 1
replace:
path: /path/to/file
regexp: 'cgroup_memory=\d+'
replace: 'cgroup_memory=1'
如果有不止一行有这个表达式,这将替换所有出现的地方。我们可以在上述任务中使用before
或参数来定位特定的。after
或者我们可以使用lineinfile 模块确保存在整行。
tasks:
- name: ensure line with cgroup_memory is present in file
lineinfile:
path: /path/to/file
regexp: 'cgroup_memory=\d+'
line: "net.ifnames=0 dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=LABEL=writable rootfstype=ext4 elevator=deadline rootwait fixrtc cgroup_memory=1 cgroup_enable=memory"
推荐阅读
- node.js - 如何响应来自 Node.js 的文件(来自 AWS)
- c# - 使用 Span 将输入字符串中的 ID 解析为长数字
在.Net - python - 将 xaxis 原点向左移动到 yaxis 交叉点
- python - 为表单创建测试:当测试断言失败时如何查看表单的错误
- angular - @Input 类变量未填充可行的成员
- python - 使用 maketrans/translate 从包含字符串的系列中删除标点符号
- python - 如何每 5 小时自动运行 Python 文件(使用 Redis 队列)
- java - 如何做一个只包含一个属性而不在 Spring Boot 中重复的列表?
- javascript - 如何在 HTML 部分多次调用 JS 代码?
- javascript - 在 d3 中链接 csv 和 json 之间的相同变量