Tự động tạo VM trên Vsphere bằng Ansible

Hướng dẫn:

 

Thực hành:

  • Bước 1: Cài Ansible trên Linux hoặc WSL (Windows Subsystem for Linux 2)
  • Bước 2: Tạo file playbook và biến tài nguyên
  •  
su -

subscription-manager repos --enable rhel-7-server-optional-rpms --enable rhel-server-rhscl-7-rpms

rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

subscription-manager register --username quangtv@nuce.edu.vn --password Nuce@1234 --auto-attach

yum install -y python3 wget ntp htop net-tools
sudo apt install python3-pip
pip3 --version

// Thư viện cho vm cài window
sudo pip3 install pywinrm

// Thư viện cho vm cài Centos
sudo pip3 install pyvmomi

Sử dụng Ansible Ad hoc

ansible appserverhostgroup -m <modulename> -a <arguments to the module>
# Run the command on all servers in a group, in this case, atlanta, in 10 parallel forks:


ansible atlanta -a "/sbin/reboot" -f 10
# If you want to run commands as a different user, it looks like this

ansible atlanta -a "/usr/bin/foo" -u username

ansible cloudera-cluster -m shell -a 'echo $JAVA'
ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts"

# Changing ownership and permissions on files
ansible webservers -m file -a "dest=/srv/foo/a.txt mode=600"
ansible webservers -m file -a "dest=/srv/foo/b.txt mode=600 owner=mdehaan group=mdehaan"
# Can also create directories, similar to mkdir -p

ansible webservers -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory"
# Xoá thư mục
ansible webservers -m file -a "dest=/path/to/c state=absent"
# Cài đặt gói yum hoặc apt

Ensure a package is installed, but don’t update it:
ansible webservers -m yum -a "name=acme state=present"

Ensure a package is installed to a specific version:
ansible webservers -m yum -a "name=acme-1.5 state=present"

Ensure a package is at the latest version:
ansible webservers -m yum -a "name=acme state=latest"

Ensure a package is not installed:
ansible webservers -m yum -a "name=acme state=absent"
# Module user và group

ansible all -m user -a "name=foo password=<crypted password here>"

ansible all -m user -a "name=foo state=absent"

# Module service

ansible webservers -m git -a "repo=git://foo.example.org/repo.git dest=/srv/myapp version=HEAD"
Ensure a service is started on all webservers:
ansible webservers -m service -a "name=httpd state=started"

Alternatively, restart a service on all webservers:
ansible webservers -m service -a "name=httpd state=restarted"

Ensure a service is stopped:
ansible webservers -m service -a "name=httpd state=stopped"