python ansible模块_ansible常用模块

一、ansible常用模块

模块是Ansible执行的最小单位,可以是由Python编写,也可以是Shell编写,也可以是由其他语言编写。

一、ping模块

测试连接可通性,没有参数。通的话返回pong。

1、使用示例

ansible all -m ping

1、可通,返回pong如下图

2、不通,返回如下图

二、setup模块

主要用于获取主机信息,在playbooks里经常会用到的一个参数gather_facts就与该模块相关。setup模块下经常使用的一个参数是filter参数,具体使用示例如下(由于输出结果较多,这里只列命令不写结果)

每个被管理节点在接收并运行管理命令之前,会将自己主机相关信息(如系统版本,主机IP地址)告知ansible管理主机

1、帮助信息

ansible-doc -s setup

--tree :将所有主机的输出信息保存到/tmp/目录下,以/etc/ansible/hosts里的主机名为文件名

ansible all-m setup -a 'filter=ansible_distribution_version' --tree /tmp/filter :过滤关键字

#ansible db-m setup -a 'filter=ansible_distribution_version'gather_subset:按子集收集信息,值有all, min, hardware, network, virtual, ohai, facter。不包含请使用!号,如,!network

2、经常获取的信息,统计表格如下

关键字说明返回值例子

ansible_nodename

节点名

"6-dns-1.hunk.tech"

ansible_fqdn

FQDN名

"6-dns-1.hunk.tech"

ansible_hostname

主机短名称

"6-dns-1"

ansible_domain

主机域名后缀

"hunk.teh"

ansible_memtotal_mb

总物理内存

"ansible_memtotal_mb": 222

ansible_swaptotal_mb

SWAP总大小

"1023"

ansible_processor

CPU信息

Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz

ansible_processor_cores

CPU核心数量

4

ansible_processor_vcpus

CPU逻辑核心数量

2

ansible_all_ipv4_addresses

有所IPV4地址

192.168.0.200

ansible_all_ipv6_addresses

所有IPV6地址

ansible_default_ipv4

默认网关的网卡配置信息

ansible_eth2

具体某张网卡信息

不同系统名称需要变化

ansible_dns

DNS设置信

ansible_architecture

系统架构

x86_64

ansible_machine

主机类型

x86_64

ansible_kernel

内核版本

"2.6.32-696.el6.x86_64"

ansible_distribution

发行版本

"CentOS"

ansible_distribution_major_version

操作系统主版本号

"6"

ansible_distribution_release

发行版名称

"Final"

ansible_distribution_version

完整版本号

"7.4.1708"

ansible_pkg_mgr

软件包管理方式

"yum"

ansible_service_mgr

进行服务方式

"systemd"

ansible_os_family

家族系列

"RedHat"

ansible_cmdline

内核启动参数

ansible_selinux

SElinux状态

"disabled"

ansible_env

当前环境变量参数

ansible_date_time

时间相关

ansible_python_version

python版本

"2.6.6"

ansible_lvm

LVM卷相关信息

ansible_mounts

所有挂载点

ansible_device_links

所有挂载的设备的UUID和卷标名

ansible_devices

所有/dev/下的正在使用的设备的信息

ansible_user_dir

执行用户的家目录

"/root"

ansible_user_gecos

执行用户的描述信息

"The root "

ansible_user_gid

执行用户的的GID

0

ansible_user_id

执行用户的的用户名

"root"

ansible_user_shell

执行用户的shell类型

"/bin/bash"

ansible_user_uid

执行用户的UID

0

3、使用范例

ansible web -m setup

执行结果

View Code

三、command模块

command 命令模块,默认模块(可省略),用于在远程执行命令(不能使用变量)

1、帮助信息

1 creates:一个文件名,当该文件存在,则该命令不执行2 free_form:要执行的linux指令3 chdir:在执行指令之前,先切换到该指定的目录4 removes:一个文件名,当该文件不存在,则该选项不执行5 executable:切换shell来执行指令,该执行路径必须是一个绝对路径

2、使用范例

# ansible all -a 'date'

四、cron模块

cron 定时任务模块

1、帮助信息

# ansible-doc -s cron-name: Manage cron.d and crontab entries

cron:

backup: # If set, create a backup of the crontab before it is modified. The location of the backup is returnedinthe `backup_file'variable by this module.

cron_file: # If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is

interpreted with respect to /etc/cron.d. (If it is absolute, it will

typically be/etc/crontab). Many linux distros expect (and some require)

the filename portion to consist solely of upper- and lower-caseletters,

digits, underscores, and hyphens. To use the `cron_file'parameter you

must specify the `user'as well.

day: # Day of the month the job should run ( 1-31, *, */2, etc )

disabled: # If the job should be disabled (commented out)in the crontab. Only has effect if `state=present'.

env: # If set, manages a crontab's environment variable. New variables are added on top of crontab. "name" and

"value"parameters are the name and the value of environment variable.

hour: # Hour when the job should run (0-23, *, */2, etc )

insertafter: # Used with `state=present'and `env'. If specified, the environment variable will be inserted after the

declaration of specified environment variable.

insertbefore: # Used with `state=present'and `env'. If specified, the environment variable will be inserted before the

declaration of specified environment variable.

job: # The command to execute or,if envis set, the value of environment variable. The command should not

contain line breaks. Requiredif state=present.

minute: # Minute when the job should run (0-59, *, */2, etc )

month: # Month of the year the job should run (1-12, *, */2, etc )

name: # Description of a crontab entry or,if env is set, the name of environment variable. Required ifstate=absent. Note that if name is not set and state=present, thena new

crontab entry will always be created, regardless of existing ones.

reboot: # If the job should be run at reboot. This option is deprecated. Users should use special_time.

special_time: # Specialtimespecification nickname.

state: # Whether to ensure the job or environment variable is present(安装) or absent(卸载).

user: # The specific user whose crontab should be modified.

weekday: # Day of the week that the job should run (0-6 for Sunday-Saturday, *, etc )

ansible-doc -s cron

1 backup:对远程主机上的原任务计划内容修改之前做备份2 cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划3 day:日(1-31,*,*/2,……)4 hour:小时(0-23,*,*/2,……)5 minute:分钟(0-59,*,*/2,……)6 month:月(1-12,*,*/2,……)7 weekday:周(0-7,*,……)8 job:要执行的任务,依赖于state=present9 name:该任务的描述10 special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly11 state:确认该任务计划是创建还是删除12 user:以哪个用户的身份执行

2、使用说明

ansible db -m cron -a 'minute="" hour="" day="" month="" weekday="" job="" name="(必须填写)" state=

1、定时设置指定值的写入即可,没有设置的可以不写(默认是*)

2、name必须写

3、state有两个状态:present(添加(默认值))or absent(移除)

3、使用范例

1、添加定时任务

ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="present"'ansible db-a "crontab -l"

结果如下图

2、移除定时任务

ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="absent"'ansible db-a "crontab -l"

结果如下图

五、user/group模块

user模块是请求的是useradd, userdel, usermod三个指令,goup模块请求的是groupadd, groupdel, groupmod 三个指令。

1、帮助信息

1、英文

# ansible-doc -s user-name: Manage user accounts

user:

append: # If `yes', add the user to the groups specified in

`groups'. If `no', user

will only be added to

thegroups specified in`groups', removing them

from all other groups.

comment: # Optionally sets the description (aka `GECOS') of user

account.

create_home: # Unless set to `no', a home directory will be made for

the user when the

account is created orifthe home directory does

not exist. Changed from

`createhome'to

`create_home'in version

2.5.

expires: # An expirytime for the user inepoch, it will be

ignored on platforms

thatdonot support

this. Currently

supported on GNU/Linux,

FreeBSD, and

DragonFlyBSD. Since

version2.6you can

remove the expirytimespecify a negative

value. Currently

supported on GNU/Linux

and FreeBSD.

force: # This only affects `state=absent', it forces removal of

the user and associated

directories on supported

platforms. The behavior

is the same as `userdel--force', check the man

page for `userdel'on

your system fordetails

and support.

generate_ssh_key: # Whether to generate a SSH keyfor the user inquestion.

This will*not*overwrite an existing

SSH key.

group: # Optionally sets the user's primary group (takes a group

name).groups: # List of groupsuser will be added to. When set to an

emptystring `''',

`null', or `~', the user

is removed from allgroupsexcept the

primary group. (`~' means `null'in YAML)

Before version 2.3, the

only input format

allowed was a comma

separatedstring. Now

this parameter accepts a

list as well as a comma

separatedstring.

hidden: # Darwin/OS X only, optionally hide the user from theloginwindow and system

preferences. The default

will be'True' ifthe

`system'option is used.

home: # Optionally set the user's home directory.

local: # Forces the use of "local"command alternatives on

platforms that implement

it. This is usefulinenvironments that use

centralized

authentification when

you want to manipulate

the local users. I.E. it

uses `luseradd` instead

of `useradd`. This

requires that these

commands exist on the

targeted host, otherwise

it will be a fatal

error.

login_class: # Optionally sets the user's login class, a feature of

most BSD OSs.

move_home: # If set to `yes'when used with `home=', attempt to move

the user's old home

directory to the

specified directoryifit isn't there already

and the old home exists.

name: # (required) Name of the user to create, remove or

modify.

non_unique: # Optionally when used with the-u option, this option

allows to change the

user ID to a non-unique

value.

password: # Optionally set the user's password to this crypted

value. On Darwin/OS X

systems, this value has

to be cleartext. Beware

of security issues. See

https://docs.ansible.com

/ansible/faq.html#how-

do-i-generate-crypted-passwords-for-the-user-modulefordetails on

various ways to generate

these password values.

password_lock: # Lock the password (usermod-L, pw lock, usermod -C).

BUT implementation

differs on different

platforms, this option

does not always mean the

user cannotloginvia

other methods. This

option does not disable

the user, only lock the

password. Do not change

the passwordinthe same

task. Currently

supported on Linux,

FreeBSD, DragonFlyBSD,

NetBSD.

remove: # This only affects `state=absent', it attempts to remove

directories associated

with the user. The

behavior is the same as

`userdel--remove',

check the man page fordetails and support.

seuser: # Optionally sets the seuser type (user_u) on selinux

enabled systems.

shell: # Optionally set the user's shell. On Mac OS X, before

version 2.5, the default

shellfor non-system

users was/usr/bin/false. Since2.5, the default shellfor non-system users on

Mac OS X is/bin/bash.

skeleton: # Optionally set a home skeleton directory. Requires

create_home option!ssh_key_bits: # Optionally specify number of bitsinSSH key to create.

ssh_key_comment: # Optionally define the commentforthe SSH key.

ssh_key_file: # Optionally specify the SSH key filename. If this is a

relative filenamethenit will be relative to

the user's home

directory.

ssh_key_passphrase: # Set a passphraseforthe SSH key. If no passphrase is

provided, the SSH key

will default to having

no passphrase.

ssh_key_type: # Optionally specify the type of SSH key to generate.

Available SSH key types

will depend on

implementation present

on target host.

state: # Whether the account should exist or not, taking actionifthe state is

different from what is

stated.

system: # When creating an account `state=present', setting this

to `yes'makes the user

a system account. This

setting cannot be

changed on existing

users.

uid: # Optionally sets the `UID'of the user.

update_password: # `always'will update passwords if they differ.

`on_create'will only

set the password fornewly created users.

ansible-doc -s user

2、中文

groups:指定用户的属组

uid:指定用的uid

password:为用户设置登陆密码,此密码是明文密码加密后的密码

update_password:always/on_create

always:只有当密码不相同时才会更新密码(默认)

on_create:只为新用户设置密码

name:指定用户名

createhome:是否创建家目录 yes|no(默认是yes)

system:是否为系统用户

remove:当state=absent时,remove=yes则表示连同家目录一起删除,等价于userdel -r(默认是no)

state:是创建还是删除 present(添加(默认值))or absent(移除)

shell:指定用户的shell环境

append:yes/no

yes:增量添加group

no:全量变更group,只设置groups指定的group组(默认)

expires:设置用户的过期时间,值是一个时间戳

3、注意事项

注:指定password参数时,不能使用后面这一串密码会被直接传送到被管理主机的/etc/shadow文件中,所以需要先将密码字符串进行加密处理。然后将得到的字符串放到password中即可。

范例

- user: name=johnd comment="John Doe" uid=1040 group=admin- user: name=james shell=/bin/bash groups=admins,developers append=yes- user: name=johnd state=absent remove=yes- user: name=james18 shell=/bin/zsh groups=developers expires=1422403387#生成密钥时,只会生成公钥文件和私钥文件,和直接使用ssh-keygen指令效果相同,不会生成authorized_keys文件。- user: name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa

2、生成加密的密码

1、安装python-pip,并安装加密函数库-passlib

yum -y install python-pip

pipinstall --upgrade pip

pipinstall passlib

2、使用加密函数库,获取密文密码

# python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"Password:

$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2.

3、创建一个系统用户,指定用户密码

ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'

4、查看测试

我们可以看到被管理主机已创建用户"testops",并且密码为密文已写入"/etc/shadow"用户文件中,尝试用ssh命令使用testops用户登录被管理主机,登录成功!

ansible db -m shell -a "cat /etc/shadow|grep testops"

ssh [email protected]

3、使用范例

1、添加用户并设置密码(加密过程如上)

ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'

结果如下图

2、删除用户(连通家目录一并删除)

ansible db -m user -a 'name="testops" state="absent" remove="yes"'

注意该用户下不能有任何进程,否则会报错如下红色部分

六、copy模块

复制文件

1、帮助信息

1 backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no2 content:用于替代"src",可以直接设定指定文件的值3 dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录4 directory_mode:递归的设定目录的权限,默认为系统默认权限5 force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes6 others:所有的file模块里的选项都可以在这里使用7 src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用"/"来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。8 validate :The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the visudo example below.

2、使用范例

1、使用src

ansible db -m copy -a 'src=/etc/hosts dest=/tmp/ owner=root mode=640 backup=no'

结果如下图

2、使用content

ansible db -m copy -a 'content="Hello ansible\n you are clever!\n" dest=/tmp/ansile.txt owner=root mode=640 backup=no'ansible db-m copy -a 'content="Hello ansible\nyou are clever!\n" dest=/tmp/ansile.txt force=yes owner=root mode=640 backup=no'

管理机操作结果如下图

目标主机结果如下图

七、file模块

设定文件属性和创建文件的符号链接

1、帮助信息

1 force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no2 group:定义文件/目录的属组3 mode:定义文件/目录的权限4 owner:定义文件/目录的属主5 path:必选项,定义文件/目录的路径6 recurse:递归的设置文件的属性,只对目录有效7 src:要被链接的源文件的路径,只应用于state=link的情况8 dest:被链接到的路径,只应用于state=link的情况9 state: directory:如果目录不存在,创建目录 file:即使文件不存在,也不会被创建 link:创建软链接 hard:创建硬链接 touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间 absent:删除目录、文件或者取消链接文件

2、使用范例

ansible db -m file -a "src=/etc/fstab dest=/tmp/fstab state=link"ansible db-m file -a "path=/tmp/fstab state=absent"ansible db-m file -a "path=/tmp/test state=touch"

八、yum模块

安装程序包

1、帮助信息

1 config_file:yum的配置文件2 disable_gpg_check:关闭gpg_check3 disablerepo:不启用某个源4 enablerepo:启用某个源5 name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径6 state:状态(present安装,absent卸载,latest最新)

2、使用示例

1、安装zsh

ansible web -m yum -a 'name=httpd state=latest'ansible web-m yum -a 'name="@Development tools" state=present'ansible web-m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'

目标主机验证

# rpm -q zsh

zsh-5.0.2-28.el7.x86_64

2、卸载

ansible web -m yum -a 'name=zsh state=absent'

目标主机验证

# rpm -q zsh

package zsh is not installed

九、service模块

1、帮助信息

1 arguments:给命令行提供一些选项2 enabled:是否开机启动 yes|no3 name:必选项,服务名称4 pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行5 runlevel:运行级别6 sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟7 state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)

2、使用示例

1、保持服务启动并设置为开机自启

ansible web -m service -a 'enabled=yes name=httpd state=started'

2、查看服务状态

ansible web -a 'service httpd status'#centOS7.x之前

ansible web-a 'chkconfig --list httpd'#centOS7.x

ansible web-a 'systemctl is-enabled httpd'

十、shell模块

尤其是用到复杂命令时(如带管道符等等)

1、帮助信息

# ansible-doc -s shell- name: Execute commands innodes.

shell:

chdir: # cd into this directory before running the command

creates: # a filename, when it already exists, this step will*not*be run.

executable: # change the shell used to execute the command. Should be an absolute path to the executable.

free_form: # (required) The shell module takes afree form command to run, as a string. There's not an actual option named "free form". See the

examples!removes: # a filename, when it does not exist, this step will*not*be run.

stdin: # Set the stdin of the command directly to the specified value.

warn: #if command warnings are on in ansible.cfg, do not warn about this particular line if set to no/false.

ansible-doc -s shell

2、使用范例

使用command模块会报错,无法得到想要的结果。

ansible web -m shell -a "ps -ef|grep httpd"

十一、script模块

将本地脚本复制到远程主机,并执行。

1、帮助信息

ansible-doc -s script-name: Runs a local script on a remote node after transferring it

script:

chdir: # cd into this directory on the remote node before running the script

creates: # a filename, when it already exists, this step will*not*be run.

decrypt: # This option controls the autodecryption of source files using vault.

executable: # Name or path of a executable to invoke the script with

free_form: # (required) Path to the local scriptfile followed by optional arguments. There is no parameter actually named 'free form'; see the

examples!removes: # a filename, when it does not exist, this step will*not* be run.

ansible-doc -s script

2、使用范例

1、实验脚本

#!/bin/bashecho "test ansible script">>/tmp/scripts.ansible

/tmp/script.sh

2、执行

ansible db -m script -a '/tmp/script.sh'

3、验证结果

十一、synchronize模块

1、帮助信息

1 archive: 归档,相当于同时开启recursive(递归)、links、perms、times、owner、group、-D选项都为yes ,默认该项为开启2 checksum: 跳过检测sum值,默认关闭3 compress:是否开启压缩4 copy_links:复制链接文件,默认为no ,注意后面还有一个links参数5 delete: 删除不存在的文件,默认no6 dest:目录路径7 dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议8 dirs:传速目录不进行递归,默认为no,即进行目录递归9 rsync_opts:rsync参数部分10 set_remote_user:主要用于/etc/ansible/hosts中定义或默认使用的用户与rsync使用的用户不同的情况11 mode: push或pull 模块,push模的话,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件

2、使用范例

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

十二、mount模块

1、帮助信息

1 dump fstype:必选项,挂载文件的类型2 name:必选项,挂载点3 opts:传递给mount命令的参数4 src:必选项,要挂载的文件5 state:必选项 present:只处理fstab中的配置 absent:删除挂载点 mounted:自动创建挂载点并挂载之 umounted:卸载

2、使用范例

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'

十三、get_url

1、帮助信息

1 sha256sum:下载完成后进行sha256 check;2 timeout:下载超时时间,默认10s3 url:下载的URL4 url_password、url_username:主要用于需要用户名密码进行验证的情况5 use_proxy:是事使用代理,代理需事先在环境变更中定义

2、使用示例

-name: download foo.conf

get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440

- name: download filewith sha256 check

get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c

十四、其他模块见链接

官方提供的可能用到模块有git、svn版本控制模块,sysctl 、authorized_key_module系统模块,apt、zypper、pip、gem包管理模块,find、template文件模块,mysql_db、redis数据库模块,url 网络模块

ansible暂停模块:https://www.cnblogs.com/Csir/p/8653114.html

你可能感兴趣的:(python,ansible模块)