Using --become for ansible_connection=local

痞子三分冷 提交于 2020-02-21 15:12:22

问题


With a personal user account (userx) I run the ansible playbook on all my specified hosts. In ansible.cfg the remote user (which can become root) to be used is:

remote_user = ansible

For the remote hosts this all works fine. It connects as the user Ansible, and executes all tasks as wished for, also changing information (like /etc/ssh/sshd_config) which requires root rights.

But now I also want to execute the playbook on the Ansible host itself. I put the following in my inventory file:

localhost ansible_connection=local

which now indeed executes on localhost. But as userx, and this results in "Access denied" for some task it needs to do.

This is of course somewhat expected, since remote_user tells something about remote, not the local user. But still, I expected that the playbook would --become locally too, to execute the tasks as root (e.g. sudo su -). It seems no to do that.

Running the playbook with --become -vvv tells me

<localhost> ESTABLISH LOCAL CONNECTION FOR USER: userx

and it seems not to try to execute the tasks with sudo. And without using sudo, the task fails.

How can I tell ansible to to use sudo / become on the local connection too?


回答1:


Nothing special is required. Proof:

  • The playbook:

    ---
    - hosts: localhost
      gather_facts: no
      connection: local
      tasks:
        - command: whoami
          register: whoami
        - debug:
            var: whoami.stdout
    
  • The execution line:

    ansible-playbook playbook.yml --become
    
  • The result:

    PLAY [localhost] ***************************************************************************************************
    
    TASK [command] *****************************************************************************************************
    changed: [localhost]
    
    TASK [debug] *******************************************************************************************************
    ok: [localhost] => {
        "changed": false,
        "whoami.stdout": "root"
    }
    
    PLAY RECAP *********************************************************************************************************
    localhost                  : ok=2    changed=1    unreachable=0    failed=0
    

The ESTABLISH LOCAL CONNECTION FOR USER: message will always show the current user, as it the account used "to connect".

Later the command(s) called from the module get(s) executed with elevated permissions.


Of course, you can add become: yes on either play level or for individual tasks.



来源:https://stackoverflow.com/questions/44901867/using-become-for-ansible-connection-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!