user2490003
user2490003

Reputation: 11900

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!

Upvotes: 4

Views: 6832

Answers (2)

Kirill
Kirill

Reputation: 474

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

Upvotes: 5

Ada Pongaya
Ada Pongaya

Reputation: 415

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

Upvotes: 3

Related Questions