首页 > 其他 > 详细

ansible自动化工具(二)

时间:2019-06-17 15:05:34      阅读:202      评论:0      收藏:0      [点我收藏+]

ping

功能:尝试链接到主机,验证并返回pong成功。

-对于Windows目标,改用win_ping模块
-不使用ICMP协议,使用SSH协议

 

例子:
#ansible webservers -m ping

10.39.2.107 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"     >返回pong表明成功通讯
}
10.39.2.106 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}

command

功能:远程节点执行命令

-变量和操作符号"<", ">", "|", ";" and "&" 不能正常工作。如果需要使用,请使用shell模块
-Ansible默认不指定模块时,将使用此模块。

  

- chdir
    命令运行前先切换到此目录
- creates 条件判断,如果文件存在,将不执行后面的命令。 #ansible webservers -m command -a creates=/app echo /app not found 10.39.2.107 | CHANGED | rc=0 >> /app not found 10.39.2.106 | CHANGED | rc=0 >> /app not found
- removes 
  条件判断,如果文件不存在,将不执行后面的命令。
  #ansible webservers -m command -a ‘removes=/app echo /app not found‘
  10.39.2.106 | SUCCESS | rc=0 >>
skipped, since /app does not exist

  10.39.2.107 | SUCCESS | rc=0 >>
skipped, since /app does not exist
- free_form
  The command module takes a free form command to run.  There is no parameter actually named ‘free form‘. 
- stdin
  将命令的stdin直接设置为指定的值
- warn
  如果ansible.cfg设置了开启警报,将不会对这一行进行警报、

shell

功能:在远程节点执行命令。与command模块使用一致,但是,变量和操作符号”<“,">" ,"|" ,";", and"&"能正常工作

下面2个例子对比能清晰的表示出不同的地方
#ansible webservers -m shell -a echo $(java -version)
10.39.2.107 | CHANGED | rc=0 >>
openjdk version "1.8.0_212"
OpenJDK Runtime Environment (build 1.8.0_212-b04)
OpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)
10.39.2.106 | CHANGED | rc=0 >>
openjdk version "1.8.0_212"
OpenJDK Runtime Environment (build 1.8.0_212-b04)
OpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)
#ansible webservers -m command -a echo $(java -version) 10.39.2.107 | CHANGED | rc=0 >> $(java -version) 10.39.2.106 | CHANGED | rc=0 >> $(java -version)

这些复杂的命令就算是用shell也有可能会失败,所以需要写到脚本里面,使用copy模块copy到远程节点,
执行,在把需要的结果拉回到执行命令的机器
#ansible webservers -m shell -a df|awk ‘{print $5}‘

script

功能:把脚本复制到远程节点后,在远程节点本地运行脚本

给定的脚本将通过远程节点上的shell环境进行处理。
这个模块在远程系统上是不需要python,就想原始脚本一样。
cat shell.sh
#!/bin/bash
echo $PATH
echo xiaolei.xing
echo $(java -version)

#ansible webservers
-m script -a ./shell.sh 10.39.2.106 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 10.39.2.106 closed.\r\n", "stderr_lines": [ "Shared connection to 10.39.2.106 closed." ], "stdout": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin\r\nxiaolei.xing\r\nopenjdk version \"1.8.0_212\"\r\nOpenJDK Runtime Environment (build 1.8.0_212-b04)\r\nOpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)\r\n\r\n", "stdout_lines": [ "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "xiaolei.xing", "openjdk version \"1.8.0_212\"", "OpenJDK Runtime Environment (build 1.8.0_212-b04)", "OpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)", "" ] } 10.39.2.107 | CHANGED => { "changed": true, "rc": 0, "stderr": "Shared connection to 10.39.2.107 closed.\r\n", "stderr_lines": [ "Shared connection to 10.39.2.107 closed." ], "stdout": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin\r\nxiaolei.xing\r\nopenjdk version \"1.8.0_212\"\r\nOpenJDK Runtime Environment (build 1.8.0_212-b04)\r\nOpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)\r\n\r\n", "stdout_lines": [ "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "xiaolei.xing", "openjdk version \"1.8.0_212\"", "OpenJDK Runtime Environment (build 1.8.0_212-b04)", "OpenJDK 64-Bit Server VM (build 25.212-b04, mixed mode)", "" ] }

copy

功能:复制文件或者目录到远程节点。默认会覆盖目标文件

backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
content:用于替换”src“,可以直接设定指定文件的内容,相当于echo重定向内容到文件
dest:必选项。要将源文件复制到远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是一个目录
directory_mode:递归的设定目录的权限,默认为系统默认权限
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
others:所有的file模块里的选项都可以在这里使用
src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径是以”/“来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。
例子:
    #ansible webservers -m copy -a src=/tmp/a.txt dest=/app backup=yes

    复制目录时,斜线不要写
    #ansible webservers -m copy -a src=/tmp/dir dest=/app backup=yes
    
    根据内容生成文件,相当于echo abc123 > /app/123.txt
    #ansible webservers -m copy -a content="abc123" dest=/app/123.txt

fetch

功能:从远程节点获取文件(只能是文件)到本地目录。默认会以主机清单中的主机名为目录,存放获取到的文件

例子:
    #ansible all -m fetch -a src=/var/log/messages dest=/app

tree -L 1 /app/
/app/
├── 10.39.2.106
├── 10.39.2.107
├── 10.39.2.113
└── 10.39.2.118

注意: src=/var/log/mess*  这种通配符语法是不支持的

file

功能:设置远程节点的文件的文件属性

force:需要在两种情况下强制创建软连接,一种是源文件不存在,但之后会创建的情况下;另一种是目标软连接已经存在,需要先取消之前的软连接,然后在创建新的软连接,有两个选项:yes|no
group:定义文件或者目录的所属组
mode:定义文件或者目录的权限
owner:定义文件或者目录的所属用户
path:必选项,定义文件或者目录的路径
recurese:递归的设置文件的属性,只针对目录有效
src:要被链接的源文件路径,只 应用于state=link的情况
dest:被连接到的路径,只应用于state=link的情况
state:操作方法
    directory:如果目录不存在,创建目录
    file:即使文件不存在,也不会创建
    link:创建软连接
    hard:创建硬连接
    touch:如果文件不存在,则会创建一个新文件,如果文件或者目录已经存在,则更新其最后修改的时间
    absent:删除目录、文件或者取消链接文件,相当于rm -ef
例子:
    创建空目录,类似于mkdir -p
    #ansible dbservers -m file -a path=/app/dir2/dir3 state=directory mode=0644 owner=mysql
    
    创建空文件,类似于touch
    #ansible dbservers -m file -a path=/app/dir1/abc.txt state=touch mode=0644 owner=mysql
    创建软连接
    #ansible dbservers -m file -a path=/app/dir1/abc.txt state=link src=/app/dir2/abc.txt   
   lrwxrwxrwx 1 root  root 17 Jun 13 02:48 abc.txt -> /app/dir1/abc.txt

hostname

功能:设置远程节点主机名

例子:
    #ansible dbservers -m hostname -a name=mysql

cron

功能:管理计划任务

backup:对远程主机上的原任务计划内容做备份
cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户任务计划
day:日(1-31,*,*/2,。。。)
hour:小时(0-23,*,*/2,……)  
minute:分钟(0-59,*,*/2,……) 
month:月(1-12,*,*/2,……) 
weekday:周(0-7,*,……)
job:要执行的任务,依赖于state=present
name:该任务的描述
special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly
state:确认该任务计划是创建还是删除
user:以那个用户身份来执行
例子:
    #ansible dbservers -m cron -a name="test cron job" minute=*/2 job="/usr/bin/wall hello world"

    禁用某个计划任务
    正确的写法:必须完整的写完,包括name等属性正确的写法:必须完整的写完,包括name等属性
    #ansible dbservers -m cron -a disabled=yes name="test cron job" minute=*/2 job="/usr/bin/wall hello world"

         #ansible dns -m cron -a disabled=yes job="/usr/bin/wall hello world"   > 这种写法是不对的,它会创建一条以下记录并禁用它

         删除计划任务
        #ansible dbservers -m cron -a state=absent name="test cron job"

yum 

功能:使用yum包管理器来管理软件包

config_file:yum的配置文件
disable_gpg_check:关闭gpg_check
disablerepo:不启用某个源
enablerepo:启动某个源
name:要进项操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径
state:Whether to install (`present or `installed, `latest), or remove (`absent or `removed) a package.
        (可选值: present, installed, latest, absent, removed) [Default: present]
例子:
    #ansible all -m yum -a name=tree state=installed

    查看
    #ansible all -m command -a rpm -qa |grep tree
    #ansible all -m shell -a rpm -qa |grep tree -o

yum_repository

功能:配置管理yum源

reposdir:repo文件存放目录
file:repo文件名,默认为name的值
name:唯一的repository ID
gpgkey:设置gpgkey
gpgcheck:设置gpg检查
enabled:设置开启关闭
bandwidth控制带宽,0为无限
state:状态(present,absent)
description:描述
例子:
    #ansible all -m yum_repository -a state=present name=epel enabled=yes gpgcheck=yes description="Aliyuan EPEL" baseurl="http://mirrors.aliyun.com/epel/6/$basearch,http://mirrors.aliyuncs.com/centos/$releasever/os/$basearch/" gpgkey="https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-6Server"

service 

功能:配置管理服务

arguments:给命令行提供一些选项,可以使用别名args
enabled:是否开机启动 yes|no
name:必选项,服务名称
pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有相应,就会通过ps指令在进程中很具该模式进项查找,如果匹配到,则认为该服务依然在运行
runlevel:定义运行级别
sleep:如果执行了restarted,则在stop和start之间沉睡几秒
state:对当前服务执行启动,停止,重启,重新加载配置等操作(started,stoped,restarted,reloaded)
例子:
    #ansible dbservers -m service -a name=httpd state=started >一次只能操作一个服务

setup

功能:收集关于远程主机的信息。

在playbooks里经常会用到一个参数gather_facts就与该模块相关

--tree:将所有主机的输出信息保存到/tmp目录下,以/etc/ansible/hosts里面的主机名为文件名
#ansible all -m setup -a filter=ansible_distribution_version --tree /tmp/

filter:过滤关键字
#ansible dbservers -m setup -a fileter=ansible_distribution_version

gather_subset:按子集收集信息,值有all,min,hardware,network,virtual,ohai,facter。不包含请使用!号,如!network
 关键字 说明  返回值例子 
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": 7822
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_address  所有IPv4地址   10.39.2.113
ansible_all_ipv6_address  所有IPV6地址    
ansible_default_ipv4  默认网关的网卡配置信息 
ansible_eth2 具体网卡信息  不同系统名称需要变化
ansible_dns DNS设置信   
ansible_architecrure  系统架构   
x86_64
ansible_machine  主机类型   
x86_64
ansible_kernel  内核版本   "3.10.0-862.el7.x86_64"
ansible_distribution  发行版本   "CentOS"
ansible_distribution_major_version  操作系统主版本号   "7"
ansible_distribution_release  发型版本名称   
"Final"
ansible_distribution_version  完整版本号   
"7.4.1708"
ansible_pkg_mgr  软件包管理方式   "yum"
ansible_service_mgr 进行服务方式  "systemd"
ansible_os_family  系列    "RedHat"
ansible_cmdline  内核启动参数   "systemd"
ansible_selinux  SElinux状态  “disabled” 
ansible_env  当前环境变量参数    
ansible_date_time  时间相关 
ansible_python_version  python版本   “2.7.5”
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  执行用的shel类型  “/bin/bash” 
 ansible_user_uid  执行用户的UID

 user

功能:管理用户账号和用户属性

      对于windows目标,请改用win_user模块

选项太多,与useradd这类系统命令差不多,详情查看

http://docs.ansible.com/ansible/latest/user_module.html

Example:
name:用户名,可以使用别名user
#ansible dbservers -m user -a name=mysql shell=/sbin/nologin system=yes comment="name is mysql"

#删除用户
ansible dbservers -m user -a name=mysql state=absent

#修改用户指定信息
ansible dbservers -m user -a name=mysql state=present comment="mysql is my"

remove:删除用户时一并删除用户家目录,需要与state=absent一起使用
ansible db -m user -a name=hunk3 state=absent remove=yes

state:操作方法。(present , absent)

groups: 添加辅助组
group: 指定用户的主组

以下这个例子注意看,group和groups所代表的含义不同。
    - name: add user
      user: name={{ username }} group=ftp groups={{ groupname }}

 

Examples
- name: Add the user johnd with a specific uid and a primary group of admin
  user:
    name: johnd
    comment: John Doe
    uid: 1040
    group: admin

- name: Add the user james with a bash shell, appending the group admins and developers to the users groups
  user:
    name: james
    shell: /bin/bash
    groups: admins,developers
    append: yes

- name: Remove the user johnd
  user:
    name: johnd
    state: absent
    remove: yes

- name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa
  user:
    name: jsmith
    generate_ssh_key: yes
    ssh_key_bits: 2048
    ssh_key_file: .ssh/id_rsa

- name: Added a consultant whose account you want to expire
  user:
    name: james18
    shell: /bin/zsh
    groups: developers
    expires: 1422403387

- name: Starting at Ansible 2.6, modify user, remove expiry time
  user:
    name: james18
    expires: -1

 group

功能:添加用户组或者删除用户组

group模块请求的是groupadd,groupdel,groupmod三个指令。

get_url

功能:从HTTP,HTTPS或者FTP下载文件

checksum:下载完成后进行checksum;格式:e.g.checksum="sha256:D98291AC[...]B6DC7B97".值有sha1, sha224, sha384, sha256, sha512, md5
timeout:下载超时时间。默认10s
url:下载的URL
url_password、url_username:主要用于需要用户名和密码验证的情况
use_proxy:是使用代理,代理需要事先在环境中定义
force:yes目标存在时是否下载,no目标文件不存在时下载
backup:创建一个包含时间戳信息的备份文件
example:
    #ansible dns -m get_url -a dest=/app/ url="https://github.com/bennojoy/nginx/archive/master.zip"

    #ansible dns -m get_url -a dest=/app/ELS.txt checksum=sha1:8c9e20bd25525c3ed04ebaa407097fe875f02b2c url="ftp://172.18.0.1/pub/Files/ELS.txt" force=yes

fail

功能:自定义消息失败

example
    - fail:
        msg:"The system may not be provisioned according to the CMDB status."
       when:cmdb_status != "to-be-staged"
    
    默认返回 Failed as requested from task

lineinfile

功能:此模块确保特定行位于文件中,或使用反向引用的正则表达式替换现有行。

      当您只想更改文件中的单行时,这非常有用。

           如果要更改多个相似的行,请查看替换模块;如果要插入/更新/删除文件中的行块,请查看blockinfile。对于其他情况,请参阅副本或模板模块。

backup:创建一个包含时间戳信息的备份文件
backrefs:为no时,如果没有匹配,则添加一行line。如果匹配了,则把匹配内容替被换为line内容。
            为yes时,如果没有匹配,则文件保持不变。如果匹配了,把匹配内容替被换为line内容。
insertafter:配合state=present。该行将在指定正则表达式的最后一个匹配之后插入。一个特殊的价值是在EOF; EOF用于在文件的末尾插入行。如果指定的正则表达式没有匹配,则将使用EOF
insertBefore:state=present。该行将在指定正则表达式的最后一个匹配之前插入。 BOF用于在文件的开头插入行。如果指定的正则表达式不匹配,则该行将被插入到文件的末尾。不能使用backrefs
valiate:在保存sudoers文件前,验证语法,如果有错,执行时,会报出来,重新编辑playbook
regexp:正则表达式
- lineinfile:
    path: /etc/selinux/config
    regexp: ‘^SELINUX=‘
    line: ‘SELINUX=disable‘
- lineinfile:
    path: /etc/sudoers
    state: absent
    regexp:‘^%wheel‘
- lineinfile:
    path: /etc/hosts
    regexp: ‘^127\.0\.0\.1‘
    line: ‘127.0.0.1 hocalhost‘
    owner: root
    group: root
    mode:0644
- lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: ‘^Listen ‘
    insertafter: ‘^#Listen ‘
    line: ‘Listen 8080‘

- lineinfile:
    path: /etc/services
    regexp: ‘^# port for http‘
    insertbefore: ‘^www.*80/tcp‘
    line: ‘# port for http by default‘

# Add a line to a file if it does not exist, without passing regexp
- lineinfile:
    path: /tmp/testfile
    line: ‘192.168.1.99 foo.lab.net foo‘

# Fully quoted because of the ‘: ‘ on the line. See the Gotchas in the YAML docs.
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: ‘^%wheel\s‘
    line: ‘%wheel ALL=(ALL) NOPASSWD: ALL‘

# Yaml requires escaping backslashes in double quotes but not in single quotes
- lineinfile:
    path: /opt/jboss-as/bin/standalone.conf
    regexp: ‘^(.*)Xms(\\d+)m(.*)$‘
    line: ‘\1Xms${xms}m\3‘
    backrefs: yes

# Validate the sudoers file before saving
- lineinfile:
    path: /etc/sudoers
    state: present
    regexp: ‘^%ADMIN ALL=‘
    line: ‘%ADMIN ALL=(ALL) NOPASSWD: ALL‘
    validate: ‘/usr/sbin/visudo -cf %s‘

replace

功能:替换一个文件中符合匹配的所有行,或者使用一个反引用的正则表达式替换所有的行

- replace:
        path: /etc/selinux/config
        regexp: ‘^SELINUX=.*‘
        replace: ‘SELINUX=disabled‘

# Before 2.3, option ‘dest‘, ‘destfile‘ or ‘name‘ was used instead of ‘path‘
- replace:
    path: /etc/hosts
    regexp: ‘(\s+)old\.host\.name(\s+.*)?$‘
    replace: ‘\1new.host.name\2‘
    backup: yes

# Replace after the expression till the end of the file (requires >=2.4)
- replace:
    path: /etc/hosts
    regexp: ‘(\s+)old\.host\.name(\s+.*)?$‘
    replace: ‘\1new.host.name\2‘
    after: ‘Start after line.*‘
    backup: yes

# Replace before the expression till the begin of the file (requires >=2.4)
- replace:
    path: /etc/hosts
    regexp: ‘(\s+)old\.host\.name(\s+.*)?$‘
    replace: ‘\1new.host.name\2‘
    before: ‘Start before line.*‘
    backup: yes

# Replace between the expressions (requires >=2.4)
- replace:
    path: /etc/hosts
    regexp: ‘(\s+)old\.host\.name(\s+.*)?$‘
    replace: ‘\1new.host.name\2‘
    after: ‘Start after line.*‘
    before: ‘Start before line.*‘
    backup: yes

- replace:
    path: /home/jdoe/.ssh/known_hosts
    regexp: ‘^old\.host\.name[^\n]*\n‘
    owner: jdoe
    group: jdoe
    mode: 0644

- replace:
    path: /etc/apache/ports
    regexp: ‘^(NameVirtualHost|Listen)\s+80\s*$‘
    replace: ‘\1 127.0.0.1:8080‘
    validate: ‘/usr/sbin/apache2ctl -f %s -t‘

- name: short form task (in ansible 2+) necessitates backslash-escaped sequences
  replace: dest=/etc/hosts regexp=‘\\b(localhost)(\\d*)\\b‘ replace=‘\\1\\2.localdomain\\2 \\1\\2‘

- name: long form task does not
  replace:
    dest: /etc/hosts
    regexp: ‘\b(localhost)(\d*)\b‘
    replace: ‘\1\2.localdomain\2 \1\2‘

更多模块说明 ,参考官网文档http://docs.ansible.com/

ansible自动化工具(二)

原文:https://www.cnblogs.com/xiaolei-xing/p/11011281.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!