Reprinted from http://www.178linux.com/79792
The Ansible command uses
Ansible syntax uses ansible-m-a
-m NAME, -module-name=NAME: Specifies the module used for execution
-u USERNAME, -user=USERNAME: Specify the remote host to run the command with USERNAME
-s, -sudo: equivalent to sudo commands on Linux systems
-USUDO_USERNAME, -sudo-user=SUDO_USERNAME: Use sudo, which is equivalent to the sudo command on Linux
-C-check Check only for non-actual execution
-e EXTRA_VARS, referencing external parameters
-i INVENTORY, specify warehouse list, default/etc/ansible/hosts
- list-hosts, listing execution host columns
Experimental framework:
Master:
Ansible 172.16.250.149
Slave:
node1 172.16.252.245
node2 172.16.251.163
node3 172.16.250.217
Installation and deployment of Ansible
The Ansible repository is not in the yum repository by default, so we need to use the following command to enable the epel repository.
[root@ansible ~]# rpm -Uvh http://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm yum install ansible
Installation Directory
Profile directory: /etc/ansible/
Execution File Directory: /usr/bin/
Lib library dependency directory: /usr/lib/pythonX.X/site-packages/ansible/
Help Document Directory: /usr/share/doc/ansible-X.X.X/
Man Document Directory: /usr/share/man/man1/
#yum install ansible -y
Configured and managed hosts directly establish ssh-based key authentication
[root@Ansible~]#ssh-keygen #Generate password Generatingpublic/privatersakeypair. Enterfileinwhichtosavethekey(/root/.ssh/id_rsa): Createddirectory'/root/.ssh'. Enterpassphrase(emptyfornopassphrase): Entersamepassphraseagain: Youridentificationhasbeensavedin/root/.ssh/id_rsa. Yourpublickeyhasbeensavedin/root/.ssh/id_rsa.pub. Thekeyfingerprintis: 2c:b0:df:16:26:8e:c7:e6:b4:c6:6a:22:e1:18:89:e9root@Ansible Thekey'srandomartimageis: +--[RSA2048]----+ || || |.| |o.| |.o.oS| |*==.| |+o..Bo| |oE..=oo| |.o.oo| +-----------------+
Add Authentication
[root@Ansible~]#ssh-copy-id root@172.16.250.149 ssh-copy-id root@172.16.252.245 ssh-copy-id root@172.16.251.163 ssh-copy-id root@172.16.250.217 [root@Ansible~]#sshroot@172.16.250.149 #Verification sshroot@172.16.252.245 sshroot@172.16.251.163 sshroot@172.16.250.217
Define hosts, add all managed hosts to/etc/ansible/hosts, otherwise cannot be managed
[root@Ansible~]#vim /etc/ansible/hosts [web] 172.16.250.149 172.16.252.245 172.16.251.163 172.16.250.217
Perform ping survival detection
[root@Ansible~]#ansible web -m ping 172.16.250.217|SUCCESS=>{ "changed":false, "ping":"pong" } 172.16.251.163|SUCCESS=>{ "changed":false, "ping":"pong" } 172.16.250.149|SUCCESS=>{ "changed":false, "ping":"pong" } 172.16.252.245|SUCCESS=>{ "changed":false, "ping":"pong" }
List execution hosts
[root@Ansible /etc/ansible]#ansible web --list-hosts hosts (4): 172.16.250.149 172.16.252.245 172.16.251.163 172.16.250.217
[root@Ansible /etc/ansible]#vim ansible.cfg host_key_checking = False [root@Ansible /etc/ansible]#useradd locy #New user [locy@Ansible ~]$ ssh-keygen [root@node1 ~]#echo "******" | passwd --stdin locy [locy@Ansible ~]$ ssh locy@172.16.252.245 [locy@node1 ~]$ [root@Ansible ~]#su locy [locy@Ansible ~]$ ssh locy@172.16.252.245 Last login: Sat Jul 8 10:29:22 2017 from 172.16.250.149 [locy@node1 ~]$ logout Connection to 172.16.252.245 closed. [locy@Ansible ~]$ ansible 172.16.252.245 -m ping 172.16.252.245 | SUCCESS => { "changed": false, "ping": "pong" }
Do secret-free sodu
[root@node1 ~]#visudo %wheel ALL=(ALL) NOPASSWD: ALL [root@node1 ~]#usermod -G wheel locy
ping 172.16.252.245, connect user locy, run as sodu
[locy@Ansible ~]$ ansible 172.16.252.245 -m ping -u locy -b 172.16.252.245 | SUCCESS => { "changed": false, "ping": "pong" } //Or use root (not recommended) [locy@Ansible ~]$ ansible 172.16.252.245 -m ping -u locy -b --become-user=root
Ansible Common Modules Detailed
Ansible [-m module_name] [-a args] [options] #ansible command format
Specify the host group or ip address Specify the parameters that the calling module passes to the module
Ansible-doc-l View all modules
ansible-doc command View command module details
Ansible-doc-s command View detailed usage of command module
Command
The command module accepts the command name followed by a space-delimited list parameter.The given command will be executed on all selected nodes.It is not handled through a shell, such as $HOME and operations such as Less Than <', >'|',';','&'Work (requires a shell module to implement these functions).
action: command
chdir #Switch to this directory before executing the command
Create #a file name, if the file exists, the command does not execute and can be used for judgment
executable #Switch shell s to execute commands, using the absolute path of the command
The free_form #Linux directive to execute is typically replaced by the -a parameter of Ansible.
removes #a file name, this file does not exist, then the command does not execute, contrary to creates
Use pwd command on all machines
-m Specifies the parameters passed to the module by the module command-a used
[root@Ansible ~]#ansible web -m command -a 'pwd' 172.16.250.217 | SUCCESS | rc=0 >> /root 172.16.252.245 | SUCCESS | rc=0 >> /root 172.16.251.163 | SUCCESS | rc=0 >> /root 172.16.250.149 | SUCCESS | rc=0 >> /root
View disk usage and transfer content to/tmp/df.txt
[root@Ansible ~]#ansible web -m shell -a 'df -h > /tmp/df.txt'
View/tmp/df.txt
[root@Ansible ~]#ansible web -m command -a 'cat /tmp/df.txt'
Add users in bulk
[root@Ansible ~]#ansible web -m command -a 'useradd Tom'
shell
If there are pipelines or variables in the command being executed, a shell is required
action: shell
Before chdir #executes, cd to the specified directory to execute the command
Create #a file name, this command does not execute when the file exists
executable #Switch shell s to execute commands, using the absolute path of the command
Commands executed by free_form #
removes #a file name, this file does not exist, then the command does not execute
View/tmp/df.txt
[root@Ansible ~]#ansible web -m shell -a 'cat /tmp/df.txt'
Set the password for the user you added last step
[root@Ansible ~]#ansible web -m shell -a 'echo rookie | passwd --stdin Tom'
copy
Copy module to copy files to managed host
action: copy
Backup #Create a backup file that includes timestamp information and, if in some way, retrieve the original file
Content #instead of src=, means that the target file content is generated directly from the information specified here
The path where the dest #remote node stores files, must be an absolute path
directory_mode #Recursive replication sets directory permissions, defaulting to system default permissions
Force #If the target host contains the file but the content is different, if set to yes, force overwrite, if set to no, copy only if the file does not exist at the target location of the target host.Default to yes
After group #has been copied to the remote host, specify the group to which the file or directory belongs
After mode #has been copied to the remote host, specify file or directory permissions, similar to those indicated by chmod as 0644
When owner #copies to a remote host, specify the file or directory owner
src #The local address of the file to be copied to the remote host, either absolute or relative.If the path is a directory, it will be copied recursively.In this case, if the path ends with'/', only the contents of the directory are copied, and if no'/'is used, the entire content including the directory is copied, similar to rsync.
Copy the local/etc/fatab file to the target host's/tmp/ansible.log, owned by roo, owned by locy, authorized by 640, and backup
[root@Ansible ~]#ansible web -m copy -a 'src=/etc/fstab dest=/tmp/ansible.log owner=root group=locy mode=640 backup=yes'
View the results of the previous step
[root@Ansible ~]#ansible web -m shell -a 'ls -l /tmp/ansible.log' 172.16.250.217 | SUCCESS | rc=0 >> -rw-r-----. 1 root locy 541 7 September 20:10 /tmp/ansible.log 172.16.250.149 | SUCCESS | rc=0 >> -rw-r-----. 1 root locy 541 7 September 20:10 /tmp/ansible.log 172.16.252.245 | SUCCESS | rc=0 >> -rw-r----- 1 root locy 541 7 September 08:10 /tmp/ansible.log 172.16.251.163 | SUCCESS | rc=0 >> -rw-r----- 1 root locy 541 7 September 20:10 /tmp/ansible.log
cron
Timing Task Module, Setting Management Nodes to Generate Timing Tasks
action: cron
Backup #If set, create a crontab backup
cron_file #If specified, use this file cron.d instead of a single user crontab
Work that day #day should run (1-31, /2, etc)
Hour #hour (0-23, /2, etc)
job #indicates what command to run
minute #minutes (0-59, /2, etc)
Month #month (1-12, /2, etc)
name #Timed Task Description
reboot #Task runs on restart, not recommended, special_time is recommended
special_time #Special time range, parameters: reboot, annual, monthly, weekly, daily, hourly
State #specifies the state, prsent means add timer task, which is also the default setting, absent means delete timer task
User #Executes as which user
weekday #week (0-6 for Sunday-Saturday, *, etc)
Save disk usage in/tmp/df.log at 3:00, 4:00, 5:00, and 6:00 a.m. each day
[root@Ansible ~]#ansible web -m cron -a 'name="harddrive check" minute="15" hour="3,4,5,6" job="df -lh >> /tmp/df.log"'
Save disk usage every 10 minutes in/tmp/df.log
[root@Ansible ~]#ansible web -m cron -a 'name="harddrive check2" minute="*/10" job="df -lh >> /tmp/df.log"' [root@Ansible ~]#crontab -l #Ansible: harddrive check 15 3,4,5,6 * * * df -lh >> /tmp/df.log #Ansible: harddrive check2 */10 * * * * df -lh >> /tmp/df.log
Remove harddrive check
[root@Ansible ~]#ansible web -m cron -a 'name="harddrive check" state=absent'
fetch
Copy remote files locally
dest #Directory where files are saved
fail_on_missing #When set to yes, if the source file is missing, the task will fail
flat #allows overriding the default behavior of attaching hostname/path/file/file to destination
src #Get files on a remote system.This must be a file, not a file directory
validate_checksum #Verify the source and target checksums after getting the file
Copy remote file/tmp/df.txt to local/root/
[root@Ansible ~]#ansible web -m fetch -a 'src=/tmp/df.txt dest=/root/'
***file
File operation module, set file properties
action: file
force #Requires forced soft connection creation in two cases, one where the source file does not exist but will be established later, and the other where the target connection already exists and the previous soft connection needs to be cancelled first, with two options:yes|no
Group #Set the group to which a file or directory belongs
mode #Set permissions for files or directories
Owner #Sets the owner of a file or directory
Path #required, defines the path to a file or directory
recurse #Sets the properties of the file recursively, only valid for directories
src #Path to be linked to, only in the case of state=link
State # directory: Create a directory if it does not exist
View/tmp/df.txt for all hosts under the web group
[root@Ansible ~]#ansible web -m shell -a 'ls -l /tmp/df.txt' 172.16.250.217 | SUCCESS | rc=0 >> -rw-r--r--. 1 root root 562 7 September 19:18 /tmp/df.txt 172.16.250.149 | SUCCESS | rc=0 >> -rw-r--r--. 1 root root 535 7 September 19:18 /tmp/df.txt 172.16.251.163 | SUCCESS | rc=0 >> -rw-r--r-- 1 root root 615 7 September 19:18 /tmp/df.txt 172.16.252.245 | SUCCESS | rc=0 >> -rw-r--r-- 1 root root 535 7 Month 9 07:18 /tmp/df.txt
Change/tmp/df.txt permissions for all hosts under the web group to 600-member master group to locy
[root@Ansible ~]#ansible web -m file -a 'path=/tmp/df.txt state=touch mode="600" owner=locy group=locy' 172.16.250.217 | SUCCESS | rc=0 >> -rw-------. 1 locy locy 562 7 September 21:41 /tmp/df.txt 172.16.250.149 | SUCCESS | rc=0 >> -rw-------. 1 locy locy 535 7 September 21:41 /tmp/df.txt 172.16.252.245 | SUCCESS | rc=0 >> -rw------- 1 locy locy 535 7 September 09:41 /tmp/df.txt 172.16.251.163 | SUCCESS | rc=0 >> -rw------- 1 locy locy 615 7 September 21:41 /tmp/df.txt
Create file directory under root
[root@Ansible ~]#ansible web -m file -a 'path=/root/file state=directory' [root@Ansible ~]#ls file
hostname
Set the host name of the system
Change 172.16.250.149 host name to master
[root@Ansible ~]#ansible 172.16.250.149 -m hostname -a 'name=master' [root@Ansible ~]#hostname master
yum
yum-based source installer
action: yum
Configuration file for conf_file # yum
disable_gpg_check #Turn off gpg_check
disablerepo #Do not enable a source
enablerepo #Enable a source
name= #Specifies the package to install, if more than one version needs to be specified, otherwise install the latest package
state #install (present), install latest, uninstall package (absent)
Install nginx for all hosts of the web group and the latest version
[root@Ansible ~]#ansible web -m yum -a 'name=nginx state=latest'
service
Service Management Module
action: service
Arguments #command line arguments passed to the service
enabled #Set service startup auto-start with yes|no parameter
name #name of control service
Pattern #Defines a pattern from which the ps directive looks in the process if there is no response when the status of the service is viewed through the status directive, and if matched, the service is still running
runlevel #Set service self-start level
Sleep #If restarted, sleep between stop and start for a few seconds
state #Start started Close stopped Restart restarted Overload reloaded
web group all hosts start nginx
[root@Ansible ~]#ansible web -m service -a 'name=nginx state=started'
web group all hosts close nginx
[root@Ansible ~]#ansible web -m service -a 'name=nginx state=stopped'
web group all hosts restart nginx
[root@Ansible ~]#ansible web -m service -a 'name=nginx state=restarted'
web group all hosts overload nginx profile
[root@Ansible ~]#ansible web -m service -a 'name=nginx state=reloaded'
web group all hosts start nginx and start/stop
[root@Ansible ~]#ansible web -m service -a 'name=nginx state=started enabled=yes/no'
group
User group module, add or remove groups
action: group
GID #Set the GID number of the group
Name= #name of management group
State #Specifies the group state, created by default, and deleted by absent
System #is set to yes, indicating the creation of a system group
Create a group named tom
[root@Ansible ~]#ansible web -m group -a 'name=tom state=present'
user
User module to manage user accounts
action: user
comment #User Description Information
createhome #Whether to create a home directory
Force #is consistent with userdel-force when using state=absent.
Group #Specify base group
Groups #Specifies additional groups, if specified (groups=) deletes all groups
Home #Specify user home directory
login_class #can set the user's Login Class FreeBSD, OpenBSD, and NetBSD systems.
move_home #If set to home=an attempt is made to move the user home directory to the specified directory
Name #Specify user name
non_unique #This option allows changing non-unique user ID values
Password #Specify user password
Remove #When using state=absent, the behavior is consistent with userdel-remove
Shell #Specify default shell
state #Sets the account status, not specified as creation, with a specified value of absent indicating deletion
System #When creating a user, set the user to be a system user.This setting cannot change an existing user
Uid #uid of specified user
update_password #Update user password
Create user Tom with user information tom is tom, uid 106, basic group tom, additional group wheel, shell type zshell, user home directory / home/tom home
[root@Ansible ~]#ansible web -m user -a 'name=tom comment="tom is tom" uid=1066 group=tom groups=wheel shell=/bin/zshell home=/home/tomhome' [root@Ansible ~]#getent passwd tom tom:x:1066:1002:tom is tom:/home/tomhome:/bin/zshell
script
Run server-side scripts at specified nodes
[root@Ansible ~]#vim test.sh #/bin/bash touch /tmp/test.sh.log #Create/tmp/test.sh.log echo "hello" >> /tmp/test.sh.log #Output date command results to/tmp/test.sh.log //Execute/root/test.sh scripts on all hosts in the web group [root@Ansible ~]#ansible web -m script -a '/root/test.sh' [root@Ansible ~]#cat /tmp/test.sh.log hello [root@node1 ~]#cat /tmp/test.sh.log hello //View/tmp/test.sh.log under 172.16.251.163 host [root@Ansible ~]#ansible 172.16.251.163 -m shell -a 'cat /tmp/test.sh.log' 172.16.251.163 | SUCCESS | rc=0 >> hello