Accessing remote_user variable

2019-04-24 09:02发布

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

4条回答
2楼-- · 2019-04-24 09:13

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

查看更多
叼着烟拽天下
3楼-- · 2019-04-24 09:29

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.

查看更多
对你真心纯属浪费
4楼-- · 2019-04-24 09:30

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
查看更多
【Aperson】
5楼-- · 2019-04-24 09:34

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
查看更多
登录 后发表回答