Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible replace code in multiple files in a directory

I'm trying to disable all repos on my server using ansible, so I'm trying to do a replace on multiple files within one directory but can't seem to get it to work any idea appreciated!

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

When I run this I just get an error like it's trying to do them all at once? How would I split them up if that was the case?

/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'} does not exist !",

update:

  - 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

The new error is following: "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'items' is undefined

Okay Getting closer! getting this error at the disable repo now:

FAILED! => {
    "failed": true,
    "msg": "'dict object' has no attribute 'stdout_lines'"
}
like image 453
completenewb Avatar asked Feb 23 '17 12:02

completenewb


People also ask

How do you replace a line in a file using Ansible?

You can use the lineinfile Ansible module to achieve that. The regexp option tells the module what will be the content to replace. The line option replaces the previously found content with the new content of your choice. The backrefs option guarantees that if the regexp does not match, the file will be left unchanged.


1 Answers

This question seems to have trailed off without fully completing... at least not with using find. Here is an example of the 2-step process that was sought after. The case for using raw for the first case has been answered. But I find this solution more appealing, even if harder:

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 }}"

This required some research on the output structure of the find command.

like image 101
AlanSE Avatar answered Sep 19 '22 02:09

AlanSE