Testinfra: Quick Start - Run Sample Test to EC2 server
In this post, I am going to try Testinfra.
what is Testinfra?
Testinfra is a server-testing framework in Python. https://testinfra.readthedocs.io/en/latest/
Similar technologies include: Serverspec, InSpec, and Goss.
test server
I have create a test server on EC2 as follows:
ssh -i test ec2-user@100.26.216.164
https://web-quickstart.blogspot.com/2021/04/terraform-ec2-instance-with-ssh-setup.html
install
% python --version
Python 3.8.5
% pip --version
pip 20.2.4
% pip install pytest-testinfra
% pip list | grep infra
pytest-testinfra 6.3.0
run locally (test Mac)
% cat root.py
def test_passwd_file(host):
passwd = host.file("/etc/passwd")
assert passwd.contains("root")
assert passwd.user == "root"
% py.test root.py
run remotely (test EC2)
Prepare ssh config like below:
% cat config
Host testserver
HostName 100.26.216.164
Port 22
User ec2-user
IdentityFile test
You can confirm the config by:
% ssh testserver -F config
Now, add options to run the test remotely.
% py.test root.py --connection=ssh --hosts=testserver --ssh-config config
check nginx installation
% cat nginx.pydef test_nginx_is_installed(host):
nginx = host.package("nginx")
assert nginx.is_installed
The test should fail as nginx is not installed yet.
% py.test nginx.py --connection=ssh --hosts=testserver --ssh-config config
Install nginx on the test server.
$ sudo yum install nginx
Running the test will result in success this time.
% py.test nginx.py --connection=ssh --hosts=testserver --ssh-config config
Comments
Post a Comment