18

This seems to work, but is it fragile? I want the owner and group in the files command to be set to someguy. I'd expect to be able to use {{ remote_user }} but that doesn't work.

This is an example playbook showing what I mean.

---
- hosts: foobar
  remote_user: someguy
  tasks:
    - name: configure /usr/src/foo
      file: 
        dest: /usr/src/foo
        state: directory
        owner: {{ ansible_ssh_user }}
        group: {{ ansible_ssh_user }}
        recurse: yes
      sudo: yes

This doesn't work:

---
- hosts: foobar
  remote_user: someguy
  tasks:
    - name: configure /usr/src/foo
      file: 
        dest: /usr/src/foo
        state: directory
        owner: {{ remote_user }}
        group: {{ remote_user }}
        recurse: yes
      sudo: yes

One or more undefined variables: 'remote_user' is undefined

Joshua Grigonis
  • 748
  • 5
  • 18

4 Answers4

13

There's also {{ ansible_ssh_user }}, which contains remote user name and seems to be accessible without issues. See also this answer.

iron77
  • 171
  • 2
  • 8
-4

When specifying variables in commands, you have to enclose them in quotes - for example:

  file: dest=/usr/src/foo state=directory owner={{ remote_user }} group={{ remote_user }} recurse=yes

should really be:

  file: dest=/usr/src/foo state=directory owner="{{ remote_user }}" group="{{ remote_user }}" recurse=yes

I'm surprised your first example works at all given the lack of quotes.

Additionally, your 'remote_user' doesn't actually have to be 'someguy' in that example as usually using sudo: yes is sufficient to have the file module set the specified owner and group correctly.

keba
  • 2,027
  • 2
  • 16
  • 20
  • It runs as root, and it has to, as the `/usr/src` subdirectory isn't writable by anyone but root. – Joshua Grigonis Jun 01 '15 at 20:01
  • Are you sure quotes are required? I'm not seeing that in the jinja docs, and if I do that the quotes end up in the final file too (so if quotes aren't allowed in that part of the file, I'm hosed). – Greg Bell Jan 03 '17 at 22:01
-4

You can try to write playbook like:

---
  - set_fact: remote_user="someguy"
  - hosts: foobar
    tasks:
      - name: configure /usr/src/foo
        file: dest=/usr/src/foo state=directory owner={{ remote_user }} group={{ remote_user }} recurse=yes
        sudo: yes
maxo
  • 69
  • 5
  • That's essentially the same, but I really despise side scrolling, and the cognitive load of thinking about multiple variables per line. It also fails exactly the same way. – Joshua Grigonis Apr 26 '17 at 21:43
-4

You can fix this by adding a vars: option

---
- hosts: foobar
  vars:
    remote_user: someguy
  tasks:
    - name: configure /usr/src/foo
      file: 
        dest: /usr/src/foo
        state: directory
        owner: {{ remote_user }}
        group: {{ remote_user }}
        recurse: yes
      sudo: yes
Moharnab Saikia
  • 487
  • 6
  • 10