Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making `get_url` and `unarchive` ansible commands idempotent

I have two ansible tasks that download an archive (the latest wordpress version, for example) and extract that archive.

- name: Download WordPress
  tags:
    - wordpress
    - wordpress:install
  get_url: "url=http://wordpress.org/wordpress-{{ wordpress_version }}.tar.gz dest={{ www_docroot }}/wordpress-{{ wordpress_version }}.tar.gz"

- name: Extract archive
  tags:
    - wordpress
    - wordpress:install
  unarchive:
    src: "{{ www_docroot }}/wordpress-{{ wordpress_version }}.tar.gz"
    dest: "{{ www_docroot }}"
    remote_src: True

I'm new to learning ansible and I'm trying to figure out: How can I make this idempotent so that it -

  1. Does not download a file if file of the same name already exists or
  2. Does not extract / expand the gzip archive if the specified target folder already exists

Thanks!

like image 721
user2490003 Avatar asked Sep 07 '25 03:09

user2490003


2 Answers

get_url module already behaves in the way you want.

You might consider completely skipping the second step if nothing is downloaded on the first step. To achieve that you register return value of the first task and check if it is changed in the second with when. In your example it will be:

- name: Download WordPress
  tags:
    - wordpress
    - wordpress:install
  get_url: "url=http://wordpress.org/wordpress-{{ wordpress_version }}.tar.gz dest={{ www_docroot }}/wordpress-{{ wordpress_version }}.tar.gz"
  register: download_wordpress

- name: Extract archive
  tags:
    - wordpress
    - wordpress:install
  unarchive:
    src: "{{ www_docroot }}/wordpress-{{ wordpress_version }}.tar.gz"
    dest: "{{ www_docroot }}"
    remote_src: True
  when: download_wordpress.changed
like image 177
Kirill Avatar answered Sep 10 '25 00:09

Kirill


consider the force option for the first query( get_url ) . consider the creates option for the second query( unarchive ) .

Sample code, you need something like this?

- name: Download WordPress
  tags:
    - wordpress
    - wordpress:install
  get_url: 
    url : "http://wordpress.org/wordpress-{{ wordpress_version }}.tar.gz dest={{ www_docroot }}/wordpress-{{ wordpress_version }}.tar.gz"
    dest: "{{ wordpress_version }}/wordpress-{{ wordpress_version }}.tar.gz"
    force : no
- name: Extract archive
  tags:
    - wordpress
    - wordpress:install
  unarchive:
    src: "{{ www_docroot }}/wordpress-{{ wordpress_version }}.tar.gz"
    dest: "{{ www_docroot }}"
    creates : "{{ www_docroot }}/wordpress"
    remote_src: True
like image 33
Ada Pongaya Avatar answered Sep 10 '25 00:09

Ada Pongaya