Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unify usage of sudo() and ansible(..., become=true, become_user="...") #692

Open
CarstenGrohmann opened this issue Apr 4, 2023 · 0 comments

Comments

@CarstenGrohmann
Copy link
Contributor

It's possible to elevate privileges with sudo() in a context manager. This works fine.

Unfortunately, the privilege elevation does not affect the direct invocation of Ansible modules. That means Ansible modules must get elevated privileges with become=True, become_user="root" additionally even if sudo permissions are already set.

Please extend Testinfra to automatically use the elevated privileges from the sudo context manager when calling Ansible modules.

Example:

def test_sudo(host):
    with open("result.txt", "w") as f:
        whoami_wo_sudo = ansiblehost.check_output("id")
        shell_wo_sudo = ansiblehost.ansible("shell id", check=False)
        with ansiblehost.sudo(user="root"):
            whoami_w_sudo = ansiblehost.check_output("id")
            shell_w_sudo = ansiblehost.ansible("shell id", check=False)
            shell_w_become = ansiblehost.ansible("shell id", check=False, become=True, become_user="root")

        print(f"""\
Test results
============

without sudo:
OS cmd "whoami":        {whoami_wo_sudo}
Ansible module "shell": {shell_wo_sudo["stdout"]}

with sudo:
OS cmd "whoami":        {whoami_w_sudo}

with sudo & without become:
Ansible module "shell": {shell_w_sudo["stdout"]}

with sudo & with become:
Ansible module "shell": {shell_w_become["stdout"]}
""", file=f)
# cat result.txt
Test results
============

without sudo:
OS cmd "whoami":        uid=999(ansible) gid=999(ansible) groups=999(ansible)
Ansible module "shell": uid=999(ansible) gid=999(ansible) groups=999(ansible)

with sudo:
OS cmd "whoami":        uid=0(root) gid=0(root) groups=0(root)

with sudo & without become:
Ansible module "shell": uid=999(ansible) gid=999(ansible) groups=999(ansible)

with sudo & with become:
Ansible module "shell": uid=0(root) gid=0(root) groups=0(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant