如何测试 bashrc 是否包含字符串

时间:2021-02-18 10:08:11

标签: ansible jinja2

基本上我想向 bash_profile 添加一个字符串,但前提是它目前不存在。必须是这样的,但不确定如何实现

"{% if aem_cms_runmode == 'author' and ~/.bash_profile contains "kobold" %}
 echo 'export PATH=/opt/day/libs/kobold/kobold-latest:$PATH' >>~/.bash_profile
{% endif %}"

我做了一些研究,但找不到在 jinja 中进行测试的正确方法。我只查看检查变量是否具有某些值。

2 个答案:

答案 0 :(得分:2)

为什么不使用lineinfile?它正是这样做的:

<块引用>

此模块确保特定行在文件中,或使用反向引用的正则表达式替换现有行。当您只想更改文件中的一行时,这主要有用。

- name: Update PATH in ~/.bash_profile
  lineinfile:
    dest: "~/.bash_profile"
    line: "export PATH=/opt/day/libs/kobold/kobold-latest:$PATH"

这是幂等的。

答案 1 :(得分:1)

如果文件中没有 export PATH,则任务将按预期工作。但是,如果已存在具有不同值的 export PATH,则结果将在文件中重复 export PATH,例如

给定文件

shell> cat bash_profile
export PATH=$PATH:/usr/sbin:/sbin:/usr/local/sbin

下面的任务

    - lineinfile:
        dest: bash_profile
        line: "export PATH=/opt/day/libs/kobold/kobold-latest:$PATH"

将添加重复的 export PATH

TASK [lineinfile] ************************************************************
--- before: bash_profile (content)
+++ after: bash_profile (content)
@@ -1 +1,2 @@
 export PATH=$PATH:/usr/sbin:/sbin:/usr/local/sbin
+export PATH=/opt/day/libs/kobold/kobold-latest:$PATH

如果要替换这样的一行,如果存在,则需要regexp。引用

<块引用>

“...当修改一行时,正则表达式通常应该匹配行的初始状态以及行替换后的状态以确保幂等性。”

例如下面的任务

    - lineinfile:
        dest: bash_profile
        regex: "^export PATH=.*$"
        line: "export PATH=/opt/day/libs/kobold/kobold-latest:$PATH"

将替换这样的行,如果它存在

TASK [lineinfile] ********************************************************
--- before: bash_profile (content)
+++ after: bash_profile (content)
@@ -1 +1 @@
-export PATH=$PATH:/usr/sbin:/sbin:/usr/local/sbin
+export PATH=/opt/day/libs/kobold/kobold-latest:$PATH

包含regexp的任务是幂等的,即文件更改后不会有任何变化

shell> cat bash_profile
export PATH=/opt/day/libs/kobold/kobold-latest:$PATH

如果您想仅在没有其他 export PATH 存在时才添加您的 export PATH,请测试它,例如仅当文件中不存在 lineinfile 时才会执行 export PATH 任务。在这种情况下,不需要 regex。根据您的需要调整图案

    - command: "grep '{{ pattern }}' bash_profile"
      register: result
      ignore_errors: true
      changed_when: false
      vars:
        pattern: "export PATH"
    - lineinfile:
        dest: bash_profile
        line: "export PATH=/opt/day/libs/kobold/kobold-latest:$PATH"
      when: result.rc|int != 0
相关问题