0

I want to set a cron entry on a remote host, but connecting to the host as a different user.

# task
- name: Cron to ls at a specific time
  cron:
    name: "perform a listing"
    weekday: "6"
    minute: "5"
    hour: "3"
    job: "/bin/ls -lR /mnt/*/"
  delegate_to: "{{ my_remote_machine }}"

Problem This is a startup script on an instance in the cloud.
The script runs as root, there fore will try to connect to {{ my_remote_machine }} as root.
root is obviously disabled by default on most cloud instances.
Because of this, I can't use the become_user keyword.

Do I have any other options?

mindrunner
  • 166
  • 3
  • 11
  • 3
    change the `remote_user` for the task to the one you can connect with. – Zeitounator Jul 10 '20 at 16:12
  • Looks like this is set at a playbook level. @Zeitounator if you add it as an answer, I'll accept it. Cheers. – mindrunner Jul 10 '20 at 17:28
  • 1
    In very short: you can set that at play and/or task level (and in depth: in vars, inventory..... see doc for that). See my answer for a brief example. – Zeitounator Jul 11 '20 at 07:07

1 Answers1

1

Simply change the remote_user for the given task to the one you can connect with on the delegated host. Here is a pseudo playbook to give you the basics.

Note: if targeting a host using ansible_connection: local (e.g. default implicit localhost), remote_user is ignored and defaults to the user launching the playbook on the controller.

---
- name: Play mixing several hosts and users
  hosts: some_host_or_group
  # Play level remote_user. In short, this is used if not overridden in task.
  # See documentation for finer grained info (define in inventory, etc...)
  remote_user: root  

  tasks:
    - name: Check who we are on current host
      command: id -a
      register: who_we_are_current
    - debug:
        var: who_we_are_current.stdout

    - name: Show we can be someone else on delegate
      command: id -a
      # Task level remote_user: overrides play
      remote_user: johnd
      delegate_to: "{{ my_remote_machine }}"
      register: who_whe_are_delegate
    - debug:
        var: who_whe_are_delegate.stdout

    - name: And of course, this works with your real task as well
      cron:
        name: "perform a listing"
        weekday: "6"
        minute: "5"
        hour: "3"
        job: "/bin/ls -lR /mnt/*/"
      remote_user: johnd
      delegate_to: "{{ my_remote_machine }}"
Zeitounator
  • 38,476
  • 7
  • 53
  • 66