简体   繁体   中英

Removing multiple rpms using ansible on RHEL machines

I wish to remove chef related rpms from a set of servers. Will this suffice in a playbook?

1st option:

- name: Check if chef rpms exist
  shell: rpm -qa *chef*
 register: rpm_output

- name: Remove chef rpms if they exist
  shell: rpm -e rpm_output
  when: rpm_output.stat.exists

2nd option:

- name: remove the chef package
  yum:
    name: chef*
    state: absent

Will the above two playbooks remove multiple rpms if the output has more than one listed?

Thanks in advance!

This is the proper way to do this in ansible, all using the yum module.

You will have to use it twice: once to list installed packages, an other time to remove the selected ones.

For this later operation, the key is to filter out the result of the previous operation to get only a list of needed names and pass it directly to yum.

    - name: List installed packages
      yum:
        list: installed
      register: yum_installed

    - name: Remove all packages starting with chef
      yum:
        name: "{{ yum_installed.results | map(attribute='name') | select('search', '^chef.*') | list }}"
        state: absent

Alternatively, you can acheive the same result using json_query:

        name: "{{ yum_installed.results | to_json | from_json | json_query(\"[?starts_with(name, 'chef')].name[]\") | list }}"

Note: to_json | from_json to_json | from_json is a workarround for a current bug in the communication between json_query and the jmespath library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM