questions

How to rewrite this Ansible playbook with a loop?

Rate this post

I make a playbook in order to make alls updates available on my WordPress serveurs.

It works but, I want to rewrite it with a loop to respect “Don’t Repeat Yourself”

It is not a playbook. Just some tasks in roles > Intranet > tasks > main.yaml

---
# Main tasks for wordpress serveurs

# Updates
- name: Update WP command line tool
  command: wp cli update
  register: wpcli_result

- name: Update WordPress Core
  command: wp core update --allow-root --path=/var/www/html
  register: update_core

- name: Update WordPress Core Data Base
  command: wp core update-db --allow-root --path=/var/www/html
  register: update_core_db

- name: Update Plugins
  command: wp plugin update --all --allow-root --path=/var/www/html
  register: update_plugins

- name: Update Themes
  command: wp theme update --all --allow-root --path=/var/www/html
  register: update_themes
...

# Debug
- name: Debug wp cli update
  ansible.builtin.debug:
    var: wpcli_result.stdout

- name: Debug wp Core update
  ansible.builtin.debug:
    var: update_core.stdout

- name: Debug wp Core update data base
  ansible.builtin.debug:
    var: update_core_db.stdout

- name: Debug wp plugins update
  ansible.builtin.debug:
    var: update_plugins.stdout

- name: Debug wp Themes update
  ansible.builtin.debug:
    var: update_themes.stdout
...

# Call to Zabbix tasks
- include: zabbix.yml

 

✔️Solution:

It is a little noisy when you look at the stdout during playbook execution but the job is done :

Edit: items.name are not necessary but I let them for better reading.

---
# Main tasks for wordpress serveurs
- name: Loop through WordPress Updates items
  command: "{{ item.command }}"
  register: var_cmd
  with_items:
    - { name: Update WP command line tool,
        command: wp cli update}
    - { name: Update WordPress Core,
        command: "wp core update {{wp_allow}} {{wp_path}}"}
    - { name: Update WordPress Core Data Base,
        command: "wp core update-db {{wp_allow}} {{wp_path}}"}
    - { name: Update Plugins,
        command: "wp plugin update --all {{wp_allow}} {{wp_path}}"}
    - { name: Update Themes,
        command: "wp theme update --all {{wp_allow}} {{wp_path}}"}
    - { name: Update Core Translations,
        command: "wp language core update {{wp_allow}} {{wp_path}}"}
    - { name: Update Plugins Translations,
        command: "wp language plugin update --all {{wp_allow}} {{wp_path}}"}
    - { name: Update Themes Translations,
        command: "wp language theme update --all {{wp_allow}} {{wp_path}}"}

- name: Debug WordPress Updates
  debug:
    msg: "{{ item.stdout_lines }}"
    verbosity: 0
  with_items: "{{ var_cmd['results'] }}"

# Call to Zabbix tasks
- include: zabbix.yml

Leave a Reply

Your email address will not be published.

Back to top button