Ansible Module Learning

Source: Internet
Author: User
Tags rsync

Ansible through the way of the module to complete some remote management work. You can view all modules through ansible-doc-l, you can use Ansible-doc-s module to view the parameters of a module, or you can use Ansible-doc Help module to view more detailed information about the module. The default module location is/usr/share/ansible. Some common modules are listed below:


1. Setup

Can be used to view some basic information about a remote host:

Ansible-i/etc/ansible/hosts test-m Setup


2.ping

Can be used to test the running state of a remote host:

Ansible test-m Ping


3.file

Setting the properties of a file

The file module contains the following options:

Force: There are two cases of forcing the creation of a soft link, one where the source file does not exist but will be established later, the other is the target soft link already exists, need to first cancel the previous soft chain, and then create a new soft chain, there are two options: Yes|no

Group: Defines the genus of files/directories

Mode: Define permissions for files/directories

Owner: Defines a file/directory owner

Path: Required option, defines the path to the file/directory

Recurse: Properties of the recursive settings file, valid only for the directory

SRC: The path of the source file to be linked, only for the case of State=link

Dest: The path to be linked to only the State=link case

State

Directory: If the directory does not exist, create a catalog

File: Will not be created even if it does not exist

Link: Create a soft link

Hard: Create a rigid link

Touch: If the file does not exist, a new file is created and the last modified time is updated if the file or directory already exists

Absent: Deleting directories, files, or unlinked files

Ansible-i/root/hosts all-m Setup View information for remote hosts

Ansible-i hosts All-m file-a "Path=/tmp/test state=touch" to create/tmp/test files remotely

Ansible-i hosts All-m file-a "Src=/etc/fstab dest=/tmp/fstab state=link" establishes a soft connection on the remote host. /etc/fstab---------->/tmp/fstab

lrwxrwxrwx. 1 root root Oct 15:28 fstab-/etc/fstab

Ansible-i hosts All-m file-a "path=/tmp/fstab state=absent" delete directory files or unlink

192.168.1.60 | Success >> {

"Changed": true,

"Path": "/tmp/fstab",

"State": "Absent"

}


192.168.1.63 | Success >> {

"Changed": true,

"Path": "/tmp/fstab",

"State": "Absent"

4.copy

Copying files to a remote host

The Copy module contains the following options:

Backup: The original file is backed up before overwriting, and the backup file contains time information. There are two options: Yes|no

Content: Used instead of "src", you can set the value of the specified file directly

Dest: Required option. The absolute path of the remote host to which the source file is to be copied, and if the source file is a directory, the path must also be a directory

Directory_mode: Recursive set permissions for the directory, default to system default permissions

Force: If the target host contains the file, but the content is different, if set to Yes, the override is enforced, and if no, the file is copied only if the target location for the destination host does not exist. The default is Yes

Others: All the options in the file module can be used here

SRC: The local address of the file to be copied to the remote host, either an absolute path or a relative path. If the path is a directory, it will be replicated recursively. In this case, if the path ends with "/", only the contents of the directory are copied, and if "/" is not used to end, the entire content, including the directory, is copied, similar to rsync.

[email protected] book]# cat Copy.yml

-Hosts:test1

Tasks

-Name:copy The file

copy:src=/root/purge_relay_logs.sh dest=/root owner=root group=root mode=755

[Email protected] book]# ansible-playbook-i/root/ansible/host/test copy.yml


PLAY [Test1] ******************************************************************


Gathering FACTS ***************************************************************

OK: [192.168.1.63]

OK: [192.168.1.76]


TASK: [Copy the file] *********************************************************

Changed: [192.168.1.63]

Changed: [192.168.1.76]


PLAY RECAP ********************************************************************

192.168.1.63:ok=2 changed=1 unreachable=0 failed=0

192.168.1.76:ok=2 changed=1 unreachable=0 failed=0

5.command

Executing commands on a remote host

The command module contains the following options:

Creates: A filename when the file exists, the command does not execute

Free_form: Linux instructions to execute

ChDir: Before executing the instruction, switch to the specified directory

Removes: A filename when the file does not exist, this option does not execute

Executable: Switch the shell to execute the instruction, the execution path must be an absolute path

Example:

Ansible test-a "/sbin/reboot"


6.shell

Switch to a shell to execute the specified instruction, with the same parameters as the command.

Example:

Ansible test-m shell-a "somescript.sh >> somelog.txt"


7.service

For managing Services

The module contains the following options:

Arguments: Provides some options for the command line

Enabled: whether to boot Yes|no

Name: Required option, service name

Pattern: Defines a pattern that, if not responded to by the status command to view the state of the service, finds it in the process based on the PS instruction and, if it matches, considers the service to be still running

RunLevel: Run Level

Sleep: If restarted is executed, sleep for a few seconds between stop and start

State: Perform start, stop, restart, reload, etc. on the current service (started,stopped,restarted,reloaded)

Example:

Ansible test-m service-a "name=httpd state=started enabled=yes"

Ansible test-m service-a "Name=foo pattern=/usr/bin/foo state=started"

Ansible test-m service-a "Name=network state=restarted args=eth0"


8.cron

For managing Scheduled Tasks

The following options are included:

Backup: Pre-schedule content modifications to the original task on the remote host

Cron_file: If this option is specified, replace the task schedule of the user under the CRON.D directory on the remote host with this file

Day: Sun (1-31,*,*/2,...... )

Hour: Hours (0-23,*,*/2, ...) )

minute: Min. (0-59,*,*/2, ... )

Month: Months (1-12,*,*/2, ...) )

Weekday: Zhou (0-7,*, ... )

Job: The task to be performed depends on the state=present

Name: Description of the task

Special_time: Specify when to execute, parameters: reboot,yearly,annually,monthly,weekly,daily,hourly

State: Verify that the task schedule is created or deleted

User: Who is executing as

Example:

Ansible test-m cron-a ' name= "Check dirs" hour= "5,2" job= "Ls-alh >/dev/null" '

Ansible test-m cron-a ' name= "a Job for reboot" Special_time=reboot job= "/some/job.sh" '

Ansible test-m cron-a ' name= "Yum AutoUpdate" weekday= "2" minute=0 hour=12 user= "root" job= "yuminteractive=0/usr/sbin/yu M-autoupdate "Cron_file=ansible_yum-autoupdate"

Ansilbe test-m cron-a ' cron_file=ansible_yum-autoupdate state=absent '

Ansible-i hosts all-m cron-a ' name= "Sync time for NTP server" minute= ' */3 ' job= "/usr/sbin/ntpdate cn.pool.ntp.org" '

192.168.1.60 | Success >> {

"Changed": true,

"Jobs": [

"Sync Time for NTP server"

]

}


192.168.1.63 | Success >> {

"Changed": true,

"Jobs": [

"Sync Time for NTP server"

]

}

Crontab-l

#Ansible: Sync time for NTP server

*/3 * * * */usr/sbin/ntpdate cn.pool.ntp.org

Ansible-i hosts all-a ' Crontab-l '

192.168.1.60 | Success | Rc=0 >>

#Ansible: Sync time for NTP server

*/3 * * * */usr/sbin/ntpdate cn.pool.ntp.org


192.168.1.63 | Success | Rc=0 >>

#Ansible: Sync time for NTP server

*/3 * * * */usr/sbin/ntpdate cn.pool.ntp.org


9.filesystem

Creating a file system on a block device

Options:

Dev: target block device

Force: Forces the creation on a device that already has a file system

Fstype: type of File system

OPTs: Options passed to the MKFS command


10.yum

Using the Yum Package Manager to manage software packages

Options:

Configuration file for Config_file:yum

Disable_gpg_check: Close Gpg_check

Disablerepo: Do not enable a source

Enablerepo: Enable a source

List

Name: You can also pass a URL or a path to a local RPM package if you want to get the names of the packages to be manipulated

State: Status (Present,absent,latest)

Example:

Ansible test-m yum-a ' name=httpd state=latest '

Ansible test-m yum-a ' name= "@Development tools" State=present "

Ansible test-m yum-a ' name=http://nginx.org/packages/centos/6/noarch/rpms/ nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present '

11.user

Manage users

Home

Groups

Uid

Password

Name

Createhome:

System

Remove

State

Shell

[email protected] ymal]# cat User.yml

-Name:create user for test group

Hosts:test

User:root

Gather_facts:false



VARs: (Introducing variables)

-User: "Toy" (variable name)



Tasks

-name:create {{user}} on test

User:name= "{{User}}"

Gather_facts's role is to gather information about the remote machine.

Ansible-playbook-i/root/hosts user.yml


PLAY [Create user for test group] *********************************************


TASK: [Create toy on VPS] *****************************************************

Changed: [192.168.1.60]

Changed: [192.168.1.63]


PLAY RECAP ********************************************************************

192.168.1.60:ok=1 changed=1 unreachable=0 failed=0

192.168.1.63:ok=1 changed=1 unreachable=0 failed=0


12.group

Administrative Groups


13.synchronize

Synchronizing files with rsync

Archive

Checksum

Delete

Dest

Src

Dest_port

Existing_only:skip createing new files on receiver

Links

Owner

Mode: (Push, pull)

Recursive

Rsync_path

Times:preserve modification Times

Example:

Src=some/relative/path dest=/some/absolute/path rsync_path= "sudo rsync"

Src=some/relative/path Dest=/some/absolute/path Archive=no Links=yes

Src=some/relative/path Dest=/some/absolute/path Checksum=yes Times=no

Src=/tmp/helloworld dest=/var/www/helloword RSYNC_OPTS=--NO-MOTD,--exclude=.git mode=pull


14.mount

Configuring mount Points

Options:

Dump

Fstype: Required option, type of Mount file

Name: Required option, mount point

OPTs: Parameters passed to the Mount command

Passno

SRC: Required option, file to mount

State: Required option

Present: Handling only the configuration in Fstab

Absent: Deleting mount points

Mounted: Automatically creates a mount point and mounts it

Umounted: Uninstalling

Example:

Name=/mnt/dvd src=/dev/sr0 fstype=iso9660 Opts=ro state=present

Name=/srv/disk src= ' Label=some_label ' state=present

Name=/home src= ' uuid=b3e48f45-f933-4c8e-a700-22a159ec9077 ' opts=noatime state=present


Ansible test-a ' dd if=/dev/zero of=/disk.img bs=4k count=1024 '

Ansible test-a ' losetup/dev/loop0/disk.img '

Ansible test-m filesystem ' fstype=ext4 force=yes opts=-f dev=/dev/loop0 '

Ansible test-m Mount ' name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw '


15.raw

Similar command, but can pass pipelines

[[email protected] ~]# ansible-i ~/hosts all-m raw-a "Rpm-qa |grep xinetd" (use raw module to see if XINETD service is installed on remote server, instructions not installed)

192.168.1.61 | FAILED | Rc=1 >>

B


[[email protected] ~]# ansible-i ~/hosts all-m yum-a "name=xinetd state=latest" (using the Yum module to install the latest version of the XINETD software in the Yum source)

192.168.1.61 | Success >> {

"Changed": true,

"MSG": "",

"RC": 0,

"Results": [

        "Loaded plugins:fastestmirror\nloading mirror speeds from cached hostfile\n * BASE:MIRRORS.S kyshe.cn\n * extras:mirrors.pubyun.com\n * updates:mirrors.pubyun.com\nsetting up Install process\nresolving dependencies\n--> Running Transaction check\n---> Package xinetd.x86_64 2:2.3.14-39.el6_4 would be installed\n-- > Finished Dependency resolution\n\ndependencies resolved\n\n================================================== ==============================\n package         Arch            version                    repository     size\n===================== ===========================================================\ninstalling:\n xinetd           x86_64          2:2.3.14-39.el6_4          base       &NB Sp  121 k\n\ntransaction summary\n================================================================================\ninstall       1 package (s) \n\ Ntotal download size:121 k\ninstalled size:259 k\ndownloading packages:\nrunning rpm_check_debug\nrunning Transaction T Est\ntransaction Test succeeded\nrunning transaction\n\r  installing:2:xinetd-2.3.14-39.el6_4.x86_64                              1/1 \n\r  verifying &NBSP: 2:xinetd-2.3.14-39.el6_4.x86_64                       &NBSP ;      1/1 \n\ninstalled:\n  xinetd.x86_64 2:2.3.14-39.el6_4             & nbsp                                 \n\ncomple Te!\n "

]

}


[[email protected] ~]# ansible-i ~/hosts all-m raw-a "Rpm-qa |grep xinetd" (Use raw module again to see if xinetd is installed)

192.168.1.61 | Success | Rc=0 >>

Xinetd-2.3.14-39.el6_4.x86_6

Ansible-i ~/hosts all-m shell-a "service xinetd restart" (Start xinetd Service using shell module)

192.168.1.61 | Success | Rc=0 >>

stopping xinetd: [FAILED]

Starting xinetd: [OK]

[[email protected] ~]# ansible-i ~/hosts all-m service-a "name=xinetd state=restarted" (also you can use the Service module to start, shut down, and restart services.) )

192.168.1.61 | Success >> {

"Changed": true,

"Name": "Xinetd",

"State": "Started"

}

Ansible all-m raw-a ' yum-y install Python-simplejson ' bulk install software

Ansible-i/root/hosts all-m copy-a "src=/root/test.sh dest=/tmp"

Ansible-i/root/ansible/host/test all-m copy-a "Src=/root/app dest=/tmp" copy the entire directory The remote server will generate the app's directory

192.168.1.61 | FAILED >> {

"Failed": true,

"Md5sum": "5d0cb5573fa5ead11bfcc701a2bb0551",

"MSG": "Aborting, Target uses selinux but Python bindings (libselinux-python) aren ' t installed!"

}


192.168.1.60 | FAILED >> {

"Failed": true,

"Md5sum": "5d0cb5573fa5ead11bfcc701a2bb0551",

"MSG": "Aborting, Target uses selinux but Python bindings (libselinux-python) aren ' t installed!"

}


192.168.1.63 | FAILED >> {

"Failed": true,

"Md5sum": "5d0cb5573fa5ead11bfcc701a2bb0551",

"MSG": "Aborting, Target uses selinux but Python bindings (libselinux-python) aren ' t installed!"

}

[[email protected] ~]# ansible-i hosts all-m script-a "/tmp/test.sh" This is because there is no test.sh the script This command means that the local script is executed on the remote machine

192.168.1.60 | FAILED = file or module does not exist:/tmp/test.sh

192.168.1.63 | FAILED = file or module does not exist:/tmp/test.sh

[[email protected] ymal]# ansible-i/root/host/hosts all-m shell-a "/root/test.sh" with the shell is the script on the remote machine to execute

192.168.1.66 | FAILED | rc=127 >>

/BIN/SH:/root/test.sh:no such file or directory


192.168.1.60 | Success | Rc=0 >>

2014-10-29 Script Testing success!


192.168.1.63 | FAILED | rc=127 >>

/BIN/SH:/root/test.sh:no such file or directory


This article from "Welcome to the Radiant" blog, declined reprint!

Ansible Module Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.