标签:special disable 权限 sed targe short -- esc 搜索
一、运维相关概念介绍/etc/ansible/ansible.cfg 配置文件: /etc/ansible/hosts 主机清单 /etc/ansible/roles /usr/bin/ansible /usr/bin/ansible-console /usr/bin/ansible-doc 查看文档 /usr/bin/ansible-galaxy /usr/bin/ansible-playbook /usr/bin/ansible-pull /usr/bin/ansible-vault
1.ansible 命令
参数:
ansible host-pattern [-f forks] [-m module] [-a args]
ansible 192.168.0.102 -a 'date'
-a 'Arguments', --args='Arguments' 命令行参数
-m NAME, --module-name=NAME 执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
-i PATH, --inventory=PATH 指定库存主机文件的路径,默认为/etc/ansible/hosts. //主机清单
-u Username, --user=Username 执行用户,使用这个远程用户名而不是当前用户
-U --sud-user=SUDO_User sudo到哪个用户,默认为 root
-k --ask-pass 登录密码,提示输入SSH密码而不是假设基于密钥的验证
-K --ask-sudo-pass 提示密码使用sudo
-s --sudo sudo运行
-S --su 用 su 命令
-l --list 显示所支持的所有模块
-s --snippet 指定模块显示剧本片段
-f --forks=NUM 并行任务数。NUM被指定为一个整数,默认是5。 #ansible testhosts -a "/sbin/reboot" -f 10 重启testhosts组的所有机器,每次重启10台
--private-key=PRIVATE_KEY_FILE 私钥路径,使用这个文件来验证连接
-v --verbose 详细信息
all 针对hosts 定义的所有主机执行
-M MODULE_PATH, --module-path=MODULE_PATH 要执行的模块的路径,默认为/usr/share/ansible/
--list-hosts 只打印有哪些主机会执行这个 playbook 文件,不是实际执行该 playbook 文件
-o --one-line 压缩输出,摘要输出.尝试一切都在一行上输出。
-t Directory, --tree=Directory 将内容保存在该输出目录,结果保存在一个文件中在每台主机上。
-B 后台运行超时时间
-P 调查后台程序时间
-T Seconds, --timeout=Seconds 时间,单位秒s
-P NUM, --poll=NUM 调查背景工作每隔数秒。需要- b
-c Connection, --connection=Connection 连接类型使用。可能的选项是paramiko(SSH),SSH和地方。当地主要是用于crontab或启动。
--tags=TAGS 只执行指定标签的任务 例子:ansible-playbook test.yml --tags=copy 只执行标签为copy的那个任务
--list-hosts 只打印有哪些主机会执行这个 playbook 文件,不是实际执行该 playbook 文件
--list-tasks 列出所有将被执行的任务
-C, --check 只是测试一下会改变什么内容,不会真正去执行;相反,试图预测一些可能发生的变化
--syntax-check 执行语法检查的剧本,但不执行它
-l SUBSET, --limit=SUBSET 进一步限制所选主机/组模式 --limit=192.168.0.15 只对这个ip执行
--skip-tags=SKIP_TAGS 只运行戏剧和任务不匹配这些值的标签 --skip-tags=copy_start
-e EXTRA_VARS, --extra-vars=EXTRA_VARS 额外的变量设置为键=值或YAML / JSON
#cat update.yml
---
- hosts: {{ hosts }}
remote_user: {{ user }}
..............
#ansible-playbook update.yml --extra-vars "hosts=vipers user=admin" 传递{{hosts}}、{{user}}变量,hosts可以是 ip或组名
-l,--limit 对指定的 主机/组 执行任务 --limit=192.168.0.10,192.168.0.11 或 -l 192.168.0.10,192.168.0.11 只对这个2个ip执行任务
2.ansible-doc是Ansible模块文档说明,
ansible-doc -l //查看所有的模块
//查看具体某模块的用法,这里如查看command模块
# ansible-doc -s command //查看详细用法
3.Ansible-galaxy的功能可以简单理解为GitHub或PIP的功能
https://galaxy.ansible.com/ 类似于github的roles库
从Ansible-galaxy上,我们可以根据下载量和关注量等信息,查找和安装优秀的Roles。
ansible-galaxy [init|info|install|list|remove]
init:初始化本地的Roles配置,以备上传Roles至galaxy。
info:列表指定Role的详细信息。
install:下载并安装galaxy指定的Roles到本地。
list:列出本地已下载的Roles。
remove:删除本地已下载的Roles。
ansible-doc -l //查看ansible支持的所有模块
ansible-galaxy list --help //查看帮助信息
ansible-galaxy install patrik.uytterhoeven.Zabbix_Server //可以下载他人写好的roles
4.ansible-lint
ansible-lint是对playbook的语法进行检查的一个工具。用法是ansible-lint playbook.yml
5.ansible-playbook
该指令是使用最多的指令,其通过读取playbook 文件后,执行相应的动作,这个后面会做为一个重点来讲。
6.ansible-pull
该指令使用需要谈到Ansible的另一种工作模式:pull 模式(Ansible默认使用push模式)。
这和通常使用的push模式工作机理刚好相反,其适用于以下场景:
(1)你有数量巨大的机器需要配置,即使使用高并发线程依旧要花费很多时间;
(2)你要在刚启动的没有网络连接的主机上运行Anisble。
通常Ansible-pull结合git和crontab一并实现,其原理如下:通过crontab定期拉取指定的Git 版本到本地,
并以指定模式自动运行预先制订好的指令。
ansible-pull [options] [playbook.yml]
*/20 * * * * root /usr/local/bin/ansible-pull -o -C 2.1.0 -d /srv/www/king-gw/ -i /etc/ansible/hosts -U git://git.kingifa.com/king-gw-ansiblepull >> /var/log/ansible-pull.log 2>&1
7.Ansible-vault主要用于配置文件加密,如编写的Playbook配置文件包含敏感信息并且不希望其他人随意查看,Ansible-vault可加密/解密这个配置文件
ansible-vault encrypt a.yml
ansible-vault decrypt a.yml
8. Ansible-console是Ansible为用户提供的一款交互式工具
9.ansible-config
list // list all current configs reading lib/constants.py and shows env and config file setting names
dump // Shows the current settings, merges ansible.cfg if specified
--only-changed // Only show configurations that have changed from the default
view // Displays the current config file
ssh-keygen
ssh-copy-id -i .ssh/id_rsa.pub root@192.168.4.110
ssh-copy-id -i .ssh/id_rsa.pub root@192.168.4.106
ansible all -m ping //使用ping模块测试主机是否在线
all :可以使用组名,websrvs,或者单个主机
四、ansible常用模块
vim /etc/ansible/ansible.cfg
forks //多个目标主机的话,一次执行5个
模块:
ansible-doc -l //列出所有模块
command|shell|copy|cron|fetch|file|hostname|yum|service|uri|user
-s //snippet:片段,ansible对应的模块的帮助片段信息,简要帮助
例如:ansible-doc -s yum
1.command //在远程主机上执行一个命令
ansible-doc -s command //这是在YAML中可以使用的
chdir:cd 到一个文件夹
creates:创建一个文件
executable:
remove:
warn:
ansible websrvs -m command -a 'ls /var' //-a指定参数
ansible websrvs -a 'ls /var' //-a指定参数, ,可省略
ansible websrvs -a 'cd /root ' -a 'ls'
注:command模块是不支持管道的,需要调用shell模块
输入输出重定向等,也要使用shell模块
ansible websrvs -a 'echo test | passwd --stdin wolf' //这个并不能修改密码,因为command是默认模块,但是不支持管道
ansible websrvs -m shell -a 'echo test | passwd --stdin wolf'
2.shell模块,支持shell特性,例如管道等
3.copy 复制本地文件到远程位置
src :absolute or relative.绝对路径或者相对路径
dest= :目标路径
mode
owner //目标文件的属主和属组
content 填充内容,而不是文件
ansible 192.168.4.110 -m copy -a "src=/etc/sysconfig/iptables-config dest=/root owner=root"
ansible 192.168.4.106 -m copy -a "content='test' dest=/root/aab mode=0600"
ansible 192.168.4.106 -m copy -a "src=/var/test dest=/var/ " //目录复制
注:如果目标文件存在则直接覆盖
4.cron //计划任务
day,hour,month,weekday,minute
state={absent|present} //缺席,出席的//是要删除任务还是添加任务
reboot,
name= //cron的名称
job=
ansible all -m cron -a "minute=*/10 job='/usr/sbin/ntpdate 202.120.2.101 &> /dev/null' name=Synctime"
ansible all -m cron -a "state=absent name=Synctime"
//删除任务,只需要指定state和name即可
5.fetch //拉取文件
dest=
src=
6.file //设置文件属性
path= //目标文件
src //源,
state {directory,link,}
mode='u=rw,g=r,o=r' //或者mode=0644
owner
group
recurse //递归修改
ansible all -m file -a "src=/tmp/fstab path=/tmp/fstab.link state=link"
//为fstab创建链接文件为fstab.link
ansible all -m file -a "path=/tmp/dd state=directory"
创建目录
ansible all -m file -a "path=/tmp/dd owner=wolf recurse=yes"
修改属性
7.hostname //管理主机名
8.yum
disablerepo
enablerepo
list
name= //包名,可以指明版本号,name-1.0即可以
state={present|latest|absent} //latest最新版本
update_cache
config_file //指定yum配置文件
ansible all -m yum -a "name=httpd state=latest"
9.service //管理服务的
enabled=1/0 ,yes/no
named=
runlevel //默认2345
sleep
state={started,stopped,restarted}
ansible all -m service -a "name=httpd state=started"
//启动服务
ansible all -m shell -a "ss -tnl |grep 80"
//查看状态信息
10.uri
url=(http|https)://hosts.domain[:port]/path
passwd
user
tiemout
method //请求的方法
11.user //管理用户账号的
name=
password
append
remove //当state=absent的时候,同时删除用户的家目录
expires
system=yes 系统用户
uid,shell,group,groups,
state={absent|present
comment,
home,move_home
ansible all -m user -a "name=user2 system=yes uid=306 state=present"
五、ansible配置文件详解
ansible.cfg //hosts会在后面解释
ansible配置的优先级:
ANSIBLE_CONFIG(环境变量)-->current 目录ansible.cfg --->家目录 .ansible.cfg-->/etc/ansible/ansible.cfg
http://docs.ansible.com/ansible/intro_configuration.html#explanation-of-values-by-section
https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
[defaults] --->通用默认配置 # some basic default values... inventory = /etc/ansible/hosts 这个是默认库文件位置,脚本,或者存放可通信主机的目录 #library = /usr/share/my_modules/ Ansible默认搜寻模块的位置 remote_tmp = $HOME/.ansible/tmp Ansible 通过远程传输模块到远程主机,然后远程执行,执行后在清理现场.在有些场景下,你也许想使用默认路径希望像更换补丁一样使用 pattern = * 如果没有提供“hosts”节点,这是playbook要通信的默认主机组.默认值是对所有主机通信 forks = 5 在与主机通信时的默认并行进程数 ,默认是5d poll_interval = 15 当具体的poll interval 没有定义时,多少时间回查一下这些任务的状态, 默认值是5秒 sudo_user = root sudo使用的默认用户 ,默认是root #ask_sudo_pass = True 用来控制Ansible playbook 在执行sudo之前是否询问sudo密码.默认为no #ask_pass = True 控制Ansible playbook 是否会自动默认弹出密码 transport = smart 通信机制.默认 值为’smart’。如果本地系统支持 ControlPersist技术的话,将会使用(基于OpenSSH)‘ssh’,如果不支持讲使用‘paramiko’.其他传输选项包括‘local’, ‘chroot’,’jail’等等 #remote_port = 22 远程SSH端口。 默认是22 module_lang = C 模块和系统之间通信的计算机语言,默认是C语言 # plays will gather facts by default, which contain information about # the remote system. # # smart - gather by default, but don't regather if already gathered # implicit - gather by default, turn off with gather_facts: False # explicit - do not gather by default, must say gather_facts: True gathering = implicit 控制默认facts收集(远程系统变量). 默认值为’implicit’, 每一次play,facts都会被收集 # additional paths to search for roles in, colon separated #roles_path = /etc/ansible/roles roles 路径指的是’roles/’下的额外目录,用于playbook搜索Ansible roles # uncomment this to disable SSH key host checking #host_key_checking = False //关闭第一次使用ansible连接客户端是输入命令提示 # change this for alternative sudo implementations sudo_exe = sudo 如果在其他远程主机上使用另一种方式执sudu操作.可以使用该参数进行更换 #what flags to pass to sudo 传递sudo之外的参数 #sudo_flags = -H # SSH timeout SSH超时时间 timeout = 10 # default user to use for playbooks if user is not specified # (/usr/bin/ansible will use current user as default) # remote_user = root 使用/usr/bin/ansible-playbook链接的默认用户名,如果不指定,会使用当前登录的用户名 # logging is off by default unless this path is defined # if so defined, consider logrotate #log_path = /var/log/ansible.log 日志文件存放路径 # default module name for /usr/bin/ansible #module_name = command ansible命令执行默认的模块 # use this shell for commands executed under sudo # you may need to change this to bin/bash in rare instances # if sudo is constrained # executable = /bin/sh 在sudo环境下产生一个shell交互接口. 用户只在/bin/bash的或者sudo限制的一些场景中需要修改 # if inventory variables overlap, does the higher precedence one win # or are hash values merged together? The default is 'replace' but # this can also be set to 'merge'. # hash_behaviour = replace 特定的优先级覆盖变量 # list any Jinja2 extensions to enable here: #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n 允许开启Jinja2拓展模块 # if set, always use this private key file for authentication, same as # if passing --private-key to ansible or ansible-playbook #private_key_file = /path/to/file 私钥文件存储位置 # format of string {{ ansible_managed }} available within Jinja2 # templates indicates to users editing templates files will be replaced. # replacing {file}, {host} and {uid} and strftime codes with proper values. ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host} 这个设置可以告知用户,Ansible修改了一个文件,并且手动写入的内容可能已经被覆盖. # by default, ansible-playbook will display "Skipping [host]" if it determines a task # should not be run on a host. Set this to "False" if you don't want to see these "Skipping" # messages. NOTE: the task header will still be shown regardless of whether or not the # task is skipped. # display_skipped_hosts = True 显示任何跳过任务的状态 ,默认是显示 # by default (as of 1.3), Ansible will raise errors when attempting to dereference # Jinja2 variables that are not set in templates or action lines. Uncomment this line # to revert the behavior to pre-1.3. # error_on_undefined_vars = False 如果所引用的变量名称错误的话, 将会导致ansible在执行步骤上失败 # by default (as of 1.6), Ansible may display warnings based on the configuration of the # system running ansible itself. This may include warnings about 3rd party packages or # other conditions that should be resolved if possible. # to disable these warnings, set the following value to False: #system_warnings = True 允许禁用系统运行ansible相关的潜在问题警告 # by default (as of 1.4), Ansible may display deprecation warnings for language # features that should no longer be used and will be removed in future versions. # to disable these warnings, set the following value to False: #deprecation_warnings = True 允许在ansible-playbook输出结果中禁用“不建议使用”警告 # (as of 1.8), Ansible can optionally warn when usage of the shell and # command module appear to be simplified by using a default Ansible module # instead. These warnings can be silenced by adjusting the following # setting or adding warn=yes or warn=no to the end of the command line # parameter string. This will for example suggest using the git module # instead of shelling out to the git command. # command_warnings = False 当shell和命令行模块被默认模块简化的时,Ansible 将默认发出警告 # set plugin path directories here, separate with colons action_plugins = /usr/share/ansible_plugins/action_plugins callback_plugins = /usr/share/ansible_plugins/callback_plugins connection_plugins = /usr/share/ansible_plugins/connection_plugins lookup_plugins = /usr/share/ansible_plugins/lookup_plugins vars_plugins = /usr/share/ansible_plugins/vars_plugins filter_plugins = /usr/share/ansible_plugins/filter_plugins # by default callbacks are not loaded for /bin/ansible, enable this if you # want, for example, a notification or logging callback to also apply to # /bin/ansible runs #bin_ansible_callbacks = False 用来控制callback插件是否在运行 /usr/bin/ansible 的时候被加载. 这个模块将用于命令行的日志系统,发出通知等特性 # don't like cows? that's unfortunate. # set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1 #nocows = 1 默认ansible可以调用一些cowsay的特性 开启/禁用:0/1 # don't like colors either? # set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1 #nocolor = 1 输出带上颜色区别, 开启/关闭:0/1 # the CA certificate path used for validating SSL certs. This path # should exist on the controlling node, not the target nodes # common locations: # RHEL/CentOS: /etc/pki/tls/certs/ca-bundle.crt # Fedora : /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem # Ubuntu : /usr/share/ca-certificates/cacert.org/cacert.org.crt #ca_file_path = # the http user-agent string to use when fetching urls. Some web server # operators block the default urllib user agent as it is frequently used # by malicious attacks/scripts, so we set it to something unique to # avoid issues. #http_user_agent = ansible-agent # if set to a persistent type (not 'memory', for example 'redis') fact values # from previous runs in Ansible will be stored. This may be useful when # wanting to use, for example, IP information from one group of servers # without having to talk to them in the same playbook run to get their # current IP information. fact_caching = memory # retry files #retry_files_enabled = False #retry_files_save_path = ~/.ansible-retry [privilege_escalation] #become=True #become_method=sudo #become_user=root #become_ask_pass=False [paramiko_connection] # uncomment this line to cause the paramiko connection plugin to not record new host # keys encountered. Increases performance on new host additions. Setting works independently of the # host key checking setting above. #record_host_keys=False # by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this # line to disable this behaviour. #pty=False [ssh_connection] # ssh arguments to use # Leaving off ControlPersist will result in poor performance, so use # paramiko on older platforms rather than removing it #ssh_args = -o ControlMaster=auto -o ControlPersist=60s # The path to use for the ControlPath sockets. This defaults to # "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with # very long hostnames or very long path names (caused by long user names or # deeply nested home directories) this can exceed the character limit on # file socket names (108 characters for most platforms). In that case, you # may wish to shorten the string below. # # Example: # control_path = %(directory)s/%%h-%%r #control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r # Enabling pipelining reduces the number of SSH operations required to # execute a module on the remote server. This can result in a significant # performance improvement when enabled, however when using "sudo:" you must # first disable 'requiretty' in /etc/sudoers # # By default, this option is disabled to preserve compatibility with # sudoers configurations that have requiretty (the default on many distros). # #pipelining = False # if True, make ansible use scp if the connection type is ssh # (default is sftp) #scp_if_ssh = True [accelerate] accelerate_port = 5099 accelerate_timeout = 30 accelerate_connect_timeout = 5.0 # The daemon timeout is measured in minutes. This time is measured # from the last activity to the accelerate daemon. accelerate_daemon_timeout = 30 # If set to yes, accelerate_multi_key will allow multiple # private keys to be uploaded to it, though each user must # have access to the system via SSH to add a new key. The default # is "no". #accelerate_multi_key = yes [selinux] # file systems that require special treatment when dealing with security context # the default behaviour that copies the existing context or uses the user default # needs to be changed to use the file system dependant context. #special_context_filesystems=nfs,vboxsf,fuse 简易配置: [defaults] inventory = /etc/ansible/hosts sudo_user=root remote_port=22 host_key_checking=False remote_user=root log_path=/var/log/ansible.log module_name=command private_key_file=/root/.ssh/id_rsa no_log:True
标签:special disable 权限 sed targe short -- esc 搜索
原文地址:http://blog.51cto.com/hmtk520/2058103