Molecule `become` best practices

Question:

What are best practices for privilege escalation when dealing with molecule?

Scenario:

I’m trying to write a role that burns an ISO to a USB. In testing this in ansible, I noticed I’m using a pattern to create a loop device. So despite not really requiring a create_loop_device play for my end goal, I decided to make one and test it just so I could use it in my other tests. Various commands for that setup require become, however molecule runs everything non-interactively (afaiui).

What I’ve tried

Using ansible native, I was able to get around this in 2 ways:

  • add -K to the molecule config
    this screws up the terminal
  • run a sudo command and then run molecule while the pam timeout is active

Neither of which seems ideal to me. Then I thought, “well, if I use docker, then ansible can just run commands as root”

My Guess

The final playbook I’m writing is intended to run on localhost. Since there are commands that genuinely need become in the task, I’d use -K when running the playbook with ansible-playbook. I would think that’s the best practice when running playbooks that need to use commands such as losetup, esp on localhost where a password prompt is typical. In molecule, I am thinking I could spin up a docker container and just run the commands as root, but there would need to be a way to ignore the become directives in the tasks it’s testing (i.e. “I am already root, I don’t need to run sudo”).

Would creating a custom image that already has the devices you want to simulate be an option?

Do you have code somewhere that we can look at/test?

Also, haven’t tested this, but I think become: is ignored if you run the playbook as root. So you might need to worry about it if you keep running as root.

On that subject.. I don’t think it’s a good idea to test a playbook as root when intended for a user.

Would creating a custom image that already has the devices you want to simulate be an option?

That’s an idea, although I am having trouble envisioning what that looks like because losetup affects the host system, afaiui.

Also, haven’t tested this, but I think become: is ignored if you run the playbook as root. So you might need to worry about it if you keep running as root.

You mean, “might not need to worry”, right?

On that subject.. I don’t think it’s a good idea to test a playbook as root when intended for a user.

This is exactly my question. I am wondering what is the ideal here?

Do you have code somewhere that we can look at/test?

Yes! converge.yml · GitHub

This currently works, but I don’t know if I’m painting myself in a corner later down the road. It seems to ignore become: now, but is this the correct way to be doing privilege escalation?