Convert chef cookbook part to ansible

Viewed 687

Could you please help me to convert this part of chef cookbook into ansible?

node['my']['domains'].each do |domain|
  execute 'install cert' do
    command "/root/bin/my_install.sh --domains #{domain}"
    not_if { File.exists?("/home/my/#{domain}/fulltext.txt") }
  end
end

I tried to play with that:

- name: Check that the fulltext.txt exists
  stat:
    path: "/home/my/{{ item }}/fulltext.txt"
  loop: "{{ my_domains }}"
  register: stat_result

- name: install cript
  command: "/root/bin/my_install.sh --domains {{ item }}"
  loop: "{{ my_domains }}"
  when: not stat_result.stat.exists

but without success.

Thanks in advance!

2 Answers

You will want the second loop: to iterate across the stat_result.results list, since each member of that list contains two relevant fields: item, containing the original iteration key, and then the stat structure that you are expecting (it looks like this, which you can see for yourself with - debug: var=stat_result)

ok: [localhost] => {
    "stat_result": {
        "changed": false,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": false,
                "failed": false,
                "invocation": {
                    "module_args": {
                        "checksum_algorithm": "sha1",
                        "follow": false,
                        "get_attributes": true,
                        "get_checksum": true,
                        "get_md5": false,
                        "get_mime": true,
                        "path": "/home/my/alpha/fulltext.txt"
                    }
                },
                "item": "alpha",
                "stat": {
                    "exists": false
                }
            },
...

thus:

- name: install cript
  command: "/root/bin/my_install.sh --domains {{ item.item }}"
  loop: "{{ stat_result.results }}"
  when: not item.stat.exists

if you find the expression item.item confusing, you can rename the loop variable to be stat_item (or whatever makes sense to you) via loop_control:

The attribute creates makes the task idempotent. Quoting

"If a matching file already exists, this step will not be run."

For example

- name: install cript
  command:
    cmd: "/root/bin/my_install.sh --domains {{ item }}"
    creates: "/home/my/{{ item }}/fulltext.txt"
  loop: "{{ my_domains }}"
Related