3

Let's say I manage file myfile.conf with Ansible, e.g.:

- template:
    src: "myfile.conf.j2"
    dest: "/etc/myfile.conf"

I can then see the diff in a dry-run, like this:

$ ansible-playbook --check --diff myplaybook.yaml

Cool. But it seems to only display the diff when the file exists on the remote host. If the file is absent, I don't see the output other than task OK.

How do I tell Ansible to show the diff if the file is absent currently?

Perhaps similar to how Git would show a diff in a commit of a newly created file in style like with /dev/null as base in the diff:

--- /dev/null
+++ b/myfile.conf.j2
gertvdijk
  • 3,504
  • 4
  • 30
  • 46

2 Answers2

4

Works for me (ansible 2.7.9):

  - name: Create haproxy.cfg
    template:
      src: templates/haproxy.cfg.j2
      dest: /var/tmp/haproxy-keepalived/haproxy.cfg

ansible-playbook --check --diff haproxy-keepalived.yaml
...
changed: [kmaster2]
--- before
+++ after: /root/.ansible/tmp/ansible-local-31057pak66sgj/tmp_de6cqgb/haproxy.cfg.j2
@@ -0,0 +1,33 @@
+global
+  daemon
+  log 127.0.0.1 local0 debug
...

Perhaps it is version-dependent or you are hitting max_diff_size (default 104448 bytes).

Mark Wagner
  • 18,019
  • 2
  • 32
  • 47
  • I believe the question is about getting the diff output even in case that the file was newly created in the task. `How do I tell Ansible to show the diff if the file is absent currently?` I didn't check if ansible actually doesn't output the diff when the file was absent when invoced with `--diff` parameter – Henrik Pingel Apr 02 '19 at 16:22
  • In my case /var/tmp/haproxy-keepalived/haproxy.cfg was newly created in the task. It was absent before. It did not exist on the remote host. – Mark Wagner Apr 02 '19 at 17:08
  • @MarkWagner Yeah, I seem to get a diff now too whoa ...? I've been playing around with strategy plugins and stdout_callback settings, which I thought I had reverted, but perhaps there were some remnants left... I will keep an eye on this if this keeps showing consistent results. – gertvdijk Apr 03 '19 at 17:30
  • @gertvdijk : With large files, you can set `ANSIBLE_MAX_DIFF_SIZE` to get around the limitation: "`diff skipped: source file size is greater than 104448`". So for example: `export ANSIBLE_MAX_DIFF_SIZE=104857600 ; ansible-playbook --check --diff myplaybook.yaml` – TrinitronX Aug 15 '19 at 15:57
2

That use case is not really implemented in Ansible but you might be able to get the output you want by adding dummy content to the file if it doesn't exist before creating it, like this:

---

- name: check if file exists
  stat:
    path: /etc/myfile.conf
  register: file

- name: add dummy line to file
  lineinfile:
    dest: /etc/myfile.conf
    state: present
    line: "bump"
    create: True
  when: file.stat.exists == False

- template:
    src: "myfile.conf.j2"
    dest: "/etc/myfile.conf"
Henrik Pingel
  • 9,380
  • 2
  • 28
  • 39