2021-10-15 09:46:54 +08:00
|
|
|
import os
|
2023-06-03 11:40:40 +08:00
|
|
|
from pathlib import Path
|
|
|
|
|
2021-10-15 09:46:54 +08:00
|
|
|
import testinfra.utils.ansible_runner
|
2023-06-03 11:40:40 +08:00
|
|
|
import yaml
|
2021-10-15 09:46:54 +08:00
|
|
|
from ansible.cli.playbook import PlaybookCLI
|
2023-06-03 11:40:40 +08:00
|
|
|
from ansible.playbook import Playbook
|
2021-10-15 09:46:54 +08:00
|
|
|
|
|
|
|
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
|
2023-06-03 11:40:40 +08:00
|
|
|
os.environ["MOLECULE_INVENTORY_FILE"]
|
|
|
|
).get_hosts("all")
|
|
|
|
|
2021-10-15 09:46:54 +08:00
|
|
|
|
|
|
|
def read_playbook(playbook):
|
|
|
|
cli_args = [os.path.realpath(playbook), testinfra_hosts]
|
|
|
|
cli = PlaybookCLI(cli_args)
|
|
|
|
cli.parse()
|
|
|
|
loader, inventory, variable_manager = cli._play_prereqs()
|
|
|
|
|
|
|
|
pb = Playbook.load(cli.args[0], variable_manager, loader)
|
|
|
|
|
|
|
|
for play in pb.get_plays():
|
|
|
|
yield variable_manager.get_vars(play)
|
|
|
|
|
2023-06-03 11:40:40 +08:00
|
|
|
|
2021-10-15 09:46:54 +08:00
|
|
|
def get_playbook():
|
2023-06-03 11:40:40 +08:00
|
|
|
playbooks_path = Path(__file__).parent.parent
|
|
|
|
with open(os.path.join(playbooks_path, "molecule.yml"), "r") as yamlfile:
|
2021-10-15 09:46:54 +08:00
|
|
|
data = yaml.load(yamlfile, Loader=yaml.FullLoader)
|
2023-06-03 11:40:40 +08:00
|
|
|
if "playbooks" in data["provisioner"].keys():
|
|
|
|
if "converge" in data["provisioner"]["playbooks"].keys():
|
|
|
|
return data["provisioner"]["playbooks"]["converge"]
|
2021-10-15 09:46:54 +08:00
|
|
|
else:
|
2023-06-03 11:40:40 +08:00
|
|
|
return os.path.join(playbooks_path, "converge.yml")
|
|
|
|
|
2021-10-15 09:46:54 +08:00
|
|
|
|
|
|
|
def test_user(host):
|
|
|
|
for vars in read_playbook(get_playbook()):
|
2023-06-03 11:40:40 +08:00
|
|
|
assert host.user(vars["user"]["name"]).exists
|
|
|
|
if "group" in vars["user"].keys():
|
|
|
|
assert host.group(vars["user"]["group"]).exists
|
2021-10-15 09:46:54 +08:00
|
|
|
else:
|
2023-06-03 11:40:40 +08:00
|
|
|
assert host.group(vars["user"]["name"]).exists
|