0

My colleagues told me to not use ~ when I write paths, so I use instead the environment variable $HOME.

I have one task which works fine:

ansible.builtin.lineinfile:
  path: $HOME/.ssh/known_hosts
  [...]

On the other hand, this one fails:

community.windows.win_lineinfile:
  line: "{{ lookup('file', '$HOME/.ssh/id_ed25519.pub') }}"
  [...]

Is it not possible to use environment variables inside a lookup?

My current solution is:

line: "{{ lookup('file', lookup('env', 'HOME')+'/.ssh/id_ed25519.pub') }}"

but it is ugly.

U880D
  • 8,601
  • 6
  • 24
  • 40
C. Güzelhan
  • 153
  • 3
  • 12

2 Answers2

2

If you are looking for a 'cleaner' way to do this, I suggest that you use the set_fact module in order to save the $HOME env in a variable. Your code would become:

- name: Save $HOME value
  set_fact:
    home: "lookup(''ansible.builtin.env', 'HOME')"

- name: Do your magic
  community.windows.win_lineinfile:
    line: "{{ lookup('file', {{ home }} + '/.ssh/id_ed25519.pub') }}"
U880D
  • 8,601
  • 6
  • 24
  • 40
Nisu
  • 230
  • 2
  • 10
0

A general approach could be just to gather_facts which are containing the environment variables of the Control Node if necessary and not available. To do so,

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Gather Env Facts of Control Node only
    delegate_to: localhost
    run_once: true
    setup:
      gather_subset:
      - "env"
      - "!all"
      - "!min"
    when: ansible_facts.env is not defined

  - name: Show env.HOME
    debug:
      msg: "{{ ansible_facts.env.HOME }}"

Further Reading

U880D
  • 8,601
  • 6
  • 24
  • 40