0
votes

I'm trying to create an Ansible task to save the content of a variable to a new file.

Using Ansible 2.5.13 and Python 2.7.5.

I've tried already to copy the content of the variable to a destination path where the file should be created...

  - name: Save alert rule example file to Prometheus
    copy:
      content: "{{ alert_rule_config }}"
      dest: /opt/compose/prom/alert_rule.yml

Tried also to create the file before copying the content of the variable

  - name: Create alert rule file
    file:
      path: /opt/compose/prom/alert_rule.yml
      state: touch

  - name: Save alert rule example file to Prometheus
    copy:
      content: "{{ alert_rule_config }}"
      dest: /opt/compose/prom/alert_rule.yml

Tried to wrap the destination path in quotes... But no matter what a directory /opt/compose/prom/alert_rule.yml/ is created!

The content of the variable is something like

  alert_rule_config:
    groups:
      - name: debug-metrics
        rules:
          - alert: DebugAlert
            expr: test_expression

I expect the file to be created (because it does not exist) and the content of the variable to be saved to the newly created file but the task fails with

FAILED! => {"changed": false, "msg": "can not use content with a dir as dest"}

I want to avoid issuing a command and would prefer to use an Ansible module.

2

2 Answers

1
votes

You need to create the target directory instead of the target file, or you will get Destination directory /opt/compose/prom does not exist in the first option or Error, could not touch target: [Errno 2] No such file or directory: '/opt/compose/prom/alert_rule.yml' in the second option.

- name: Create alert rule containing directory
  file:
    path: /opt/compose/prom/
    state: directory
- name: Save alert rule example file to Prometheus
  copy:
    content: "{{ alert_rule_config }}"
    dest: /opt/compose/prom/alert_rule.yml

But as @Calum Halpin says, if during your tests you did an error and created a directory /opt/compose/prom/alert_rule.yml/, you need to remove it before.

0
votes

This will happen if a directory /opt/compose/prom/alert_rule.yml already exists when your tasks are run.

To remove it as part of your tasks add

- file:
    path: /opt/compose/prom/alert_rule.yml
    state: absent

ahead of your other tasks.