【问题标题】:Ansible replace code in multiple files in a directoryAnsible替换目录中多个文件中的代码
【发布时间】:2017-07-13 22:18:50
【问题描述】:

我正在尝试使用 ansible 禁用我的服务器上的所有 repos,因此我正在尝试对一个目录中的多个文件进行替换,但似乎无法让它发挥作用!

tasks:

  - name: get repo names
    raw: find /etc/yum.repos.d/ -type f -name "*.repo"
    register: repos

  - name: disable all repos
    replace: dest={{repos}} regexp="enabled=1" replace="enabled=0"
    with_items: repos.stdout_lines

当我运行它时,我只是得到一个错误,就像它试图一次完成它们一样?如果是这样,我将如何拆分它们?

/etc/yum.repos.d/CentOS-Debuginfo.repo\r\n/etc/yum.repos.d/epel.repo\r\n/etc/yum.repos.d/CentOS-Base。 repo\r\n'} 不存在!",

更新:

  - find:
      paths: "/etc/yum.repos.d/"
      patterns: "*.repo"
    register: repos

  - name: disable all repos
    replace: dest={{items}} regexp="enabled=1" replace="enabled=0"
    with_items: repos

新错误如下: "msg": "'args' 字段的值无效,似乎包含未定义的变量。错误是:'items' 未定义

好的,越来越近了!现在在禁用回购中收到此错误:

FAILED! => {
    "failed": true,
    "msg": "'dict object' has no attribute 'stdout_lines'"
}

【问题讨论】:

    标签: linux centos ansible


    【解决方案1】:

    这个问题似乎没有完全完成……至少没有使用find。这是一个被追捧的两步过程的例子。第一种情况使用raw 的情况已得到解答。但我发现这个解决方案更有吸引力,即使更难:

    tasks:
    - name: Find all of the files inside this directory
      find:
        paths: "/etc/yum.repos.d/"
        patterns: "*.repo"
      register: repos
    
    - name: Replace foo with bar in the files
      replace:
        path: "{{ item.path }}"
        regexp: 'foo'
        replace: 'bar'
      with_items: "{{ repos.files }}"
    

    这需要对find 命令的输出结构进行一些研究。

    【讨论】:

    • 这对我有用。 Ansible 文档说您应该在 YAML 中使用 ansible.builtin.replace 而不是 replace
    【解决方案2】:

    这是“一次全部尝试”,因为您将前一个任务的整个输出作为dest 的参数提供:

    dest={{repos}}
    

    相反,您应该提供您迭代的项目:

    dest={{item}}
    

    您也不要在with_items 中引用变量。

    第二个任务应该是这样的:

    - name: disable all repos
      replace: dest={{item}} regexp="enabled=1" replace="enabled=0"
      with_items: "{{ repos.stdout_lines }}"
    

    此外,您可以使用find module 代替raw 命令。

    【讨论】:

    • 您好上面更新了抱歉没有意识到它不会在评论中显示好!
    • 谢谢你,我认为 find 没有正确存储禁用读取的信息?添加新错误,再次感谢!
    • 尝试类似- name: Find files with yaml find: path: "$HOME/kube_objs/" pattern: "*.yaml" register: kubespecs - name: Replace docker repository replace: dest={{ item }} regexp="11.168.25.68" replace='x' with_items: "{{ kubespecs.stdout_lines }}" 但得到与上面提到的相同的错误 "'dict object' has no attribute 'stdout_lines'"} 尝试使用 {{ kubespecs }} 而不是 {{item}} 作为好吧,请帮忙。
    • 你解释她应该使用 {{item}},然后你继续使用 {{repos}}。这没什么用。
    • @bviktor 感谢您发现错字并告诉我。
    【解决方案3】:

    错误是:“项目”未定义

    这是因为你必须使用“项目”而不是项目中的项目

     dest=
    
    (dest={{item}})
    

    ,但使用items

    所以正确的方法是:

    - name: disable all repos
      replace: dest={{item}} regexp="enabled=1" replace="enabled=0"
      with_items: repos
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-16
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      相关资源
      最近更新 更多