Create new file in GitLab via Ansible

Viewed 39

The script for my ansible job is located in a gitlab repository.
E.g.: /Ansible/job.yaml

I want to create a new file from my Ansible job that contain the response of another Ansible job that I run in the same location as my job script.
E.g.: /Ansible/ouput.txt

Is it possible? Usually I put the file to the server host but this time I need it to be in GitLab.

1 Answers

Given that GitLab do let you write in that folder indeed, you can:

So, something like:

- copy:
    content: "{{ some_other_registered_task_output }}"
    dest: "{{ playbook_dir }}/output.txt"
  delegate_to: localhost

Mind that if you are targeting multiple hosts in that playbook, you will have to aggregate all nodes registered output, otherwise you will end up with the output of one node only.

Which you can achieve with something like:

- copy:
    content: "{{
        hostvars
        | dict2items
        | selectattr('key', 'in', ansible_play_hosts)
        | map(attribute='value.some_other_registered_task_output')
        | join('\n\n')
      }}"
    dest: "{{ playbook_dir }}/output.txt"
  delegate_to: localhost

For example, the two tasks:

- command: echo '{{ inventory_hostname }}'
  register: some_other_registered_task_output

- copy:
    content: "{{
        hostvars
        | dict2items
        | selectattr('key', 'in', ansible_play_hosts)
        | map(attribute='value.some_other_registered_task_output.stdout')
        | join('\n\n')
      }}"
    dest: "{{ playbook_dir }}/output.txt"
  delegate_to: localhost

Run on nodes called node1, node2 and node3, would create a file output.txt, in the same folder as the playbook, on the controller, containing:

node3

node1

node2
Related