Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Local File With Ansible Template From Variables

I'm running an ansible playbook against a number of ec2 instances to check if a directory exists.

---
- hosts: all
  become: true
  tasks:
  - name: Check if foo is installed
    stat:
      path:
        /etc/foo
    register: path
  - debug: msg="{{path.stat.exists}}"

And I would like to generate a localfile that lists the private IP addresses of the ec2 instances and states whether or not the directory foo does exist.

I can get the private IP addresses of the instances with this task

  - name: Get info from remote
    shell: curl http://169.254.169.254/latest/meta-data/local-ipv4
    register: bar
  - debug: msg="{{bar.stdout}}"

How do I create a local file with content

IP address: 10.100.0.151 directory foo - false
IP address: 10.100.0.152 directory foo - true

I've tried adding a block for this as such

- hosts: localhost
  become: false
  vars:
    installed: "{{bar.stdout}}"
    status:    "{{path.stat.exists}}"
    local_file: "./Report.txt"
  tasks:

  - name: Create local file with info
    copy:
      dest: "{{ local_file }}"
      content: |
        "IP address {{ installed }} foo - {{ status }}"

But it doesn't look like I can read values of variables from earlier steps.

What am I doing wrong please?

like image 204
Metro Avatar asked Oct 29 '25 19:10

Metro


1 Answers

A similar question has been answered here.

Basically what you want is to reference it through the host var variable.

This should work.

- hosts: localhost
  become: false
  vars:
    local_file: "./Report.txt"
  tasks:

  - name: Create local file with info
    lineinfile:
      path: "{{ local_file }}"
      line:
        "IP Address: {{ hostvars[item]['bar'].stdout }} - Installed: {{ hostvars[item]['path'].stat.exists }}"
    with_items: "{{ query('inventory_hostnames', 'all') }}"

And this should populate your local ./Report.txt file, with the info you need.

like image 173
Hammed Avatar answered Nov 01 '25 14:11

Hammed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!