【问题标题】:How to use regex with ansible file module如何将正则表达式与 ansible 文件模块一起使用
【发布时间】:2020-04-12 13:18:21
【问题描述】:

我有以下文件模块,它涉及远程主机上的文件。

 - name: create file
   file:
     path: "/oracle/{{ inventory_hostname }}/del.tmp"
     state: touch
   register: direxists

 - fail:
     msg: "Directory missing"
   when: direxists.changed == False

问题出在我可能拥有/oracle/Oracle 文件夹的目标主机上。字母“o”可能不区分大小写。因此,我希望正则表达式能够工作

 path: "/[Oo]racle/{{ inventory_hostname }}/del.tmp"

但不幸的是,文件模块不支持这样的正则表达式。

我将不得不退回到shell 模块并改用 Unix 命令;这是我不想要的。

如果 /Oracle 或 /oracle 目录都丢失,我希望播放失败。如果存在 [Oo]racle 目录中的任何人,我的游戏应该不会失败。

我怎样才能达到这个要求?

【问题讨论】:

  • 将所有机器上的Oracle 重命名为oracle,一劳永逸。确保通过自动化在新机器上正确创建该文件夹。然后你就不必再担心了。 Unix 是区分大小写的,没有简单的方法告诉 ansible 在任何一种情况下创建一个文件,而不是非常冗长(例如使用 stat 模块和测试)或下降到 shell

标签: file ansible touch createfile


【解决方案1】:

找到目录。如果没有找到则失败。切换第一个字母的大小写创建链接。这样 /Oracle 和 /oracle 都会存在并指向同一个目录。

    - find:
        paths: /
        patterns: '[oO]racle'
        file_type: directory
      register: result

    - fail:
        msg: Directory is missing. Play failed.
      when: result.matched == 0

    - set_fact:
        mylink: "{{ mydir[0] ~ myswitch[mydir[1]] ~  mydir[2:] }}"
      vars:
        mydir: "{{ result.files.0.path }}"
        myswitch:
          'o': 'O'
          'O': 'o'

    - file:
        state: link
        src: "{{ result.files.0.path }}"
        dest: "{{  mylink }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2015-12-18
    • 2016-12-29
    • 2011-06-19
    相关资源
    最近更新 更多