Operations-ansible-01
Operations-ansible-01
ansible
features
模塊化,調(diào)用特定的模塊來(lái)完成特定任務(wù) 基于python語(yǔ)言實(shí)現(xiàn),由paramiko、pyYAML和jinja2三個(gè)關(guān)鍵模塊實(shí)現(xiàn) 部署簡(jiǎn)單,agentless 主從模式 支持自定義模塊 支持playbook 冪等性:運(yùn)行多次,結(jié)果相同組成部分
ansible core host inventory:主機(jī)庫(kù),定義了ansible能夠管控的主機(jī)列表 connection plugins:用于管理主機(jī)的插件,一般是SSH的API向主機(jī)建立會(huì)話并發(fā)送指令 modules:各種core modulescustom modules playbooks:定制好的模塊和命令配置文件
主配置文件
/etc/ansible/ansible.cfgHost Inventory
/etc/ansible/hostsansible命令
ansible <host-pattern> [-f forks] [-m module_name] [-a args]host-patternA name of a group in the inventory file, a shell-like glob selecting hosts in inventory file, or any combination of the two separated by semicolons./etc/ansible/hostsINI風(fēng)格,中括號(hào)中的字符是組名;一個(gè)主機(jī)可同時(shí)屬于多個(gè)組-i PATH, --inventory=PATHThe PATH to the inventory hosts file, which defaults to /etc/ansible/hosts.-a 'ARGUMENTS', --args='ARGUMENTS'The ARGUMENTS to pass to the module.–
[root@husa ansible]# ansible-doc --help Usage: ansible-doc [options] [module...]Show Ansible module documentationOptions:--version show program's version number and exit-h, --help show this help message and exit-M MODULE_PATH, --module-path=MODULE_PATHAnsible modules/ directory-l, --list List available modules-s, --snippet Show playbook snippet for specified module(s) #查看模塊的使用參數(shù)-v Show version number and exit常用模塊
ansible-doc -l查看支持的模塊
[root@localhost .ssh]# ansible-doc -l ... apt Manages apt-packages apt_key Add or remove an apt key apt_repository Add and remove APT repositories apt_rpm apt_rpm package manager assemble Assembles a configuration file from frag... assert Fail with custom message at Schedule the execution of a command or s... authorized_key Adds or removes an SSH authorized key azure create or terminate a virtual machine in... bigip_facts Collect facts from F5 BIG-IP devices bigip_monitor_http Manages F5 BIG-IP LTM http monitors bigip_monitor_tcp Manages F5 BIG-IP LTM tcp monitors ...模塊的參數(shù)是KV數(shù)據(jù)
-a key=value
command
-a 'COMMAND' [root@localhost .ssh]# ansible all -m command -a 'ls' 172.16.11.101 | success | rc=0 >> anaconda-ks.cfg httpd.csr172.16.11.102 | success | rc=0 >> anaconda-ks.cfgcommand是默認(rèn)模塊,可以省略不寫(xiě)即ansible all -a ‘ls’
默認(rèn)模塊,這個(gè)模塊的參數(shù)不是KV格式而是直接給出命令;這個(gè)模塊不能使用 管道
ping
A trivial test module, this module always returns pong on successful contact. It does not make sense in playbooks, but it is useful from /usr/bin/ansible to verify the ability to login and that a usable python is configured. This is NOT ICMP ping, this is just a trivial test module. [root@localhost .ssh]# ansible 172.16.11.101 -m ping 172.16.11.101 | success >> {"changed": false, "ping": "pong" }user
name yes Name of the user to create, remove or modify.
state no [present|absent] Whether the account should exist or not, taking action if the state is different from what is stated.
system no [yes|no] When creating an account, setting this to yes makes the user a system account. This setting cannot be changed on existing users.
group
-a 'name= state={present|absent} gid= system='[root@localhost ~]# ansible-doc -s group- name: A d d o r r e m o v e g r o u p saction: groupgid # Optional `GID' to set for the group.name= # Name of the group to manage.state # Whether the group should be present or not on the remote host.system # If `yes', indicates that the group created is a system group.file
Sets attributes of files, symlinks, and directories, or removes files/symlinks/directories. Many other modules support the same options as the file module - including copy, template, and assemble.
-a 'path= mode= owner= group= state={file|directory|link|hard|touch|absent} src=' [root@localhost ~]# ansible all -m file -a 'path=/root/ansi state=directory mode=755 owner=root group=root' 172.16.11.102 | success >> {"changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/root/ansi", "secontext": "unconfined_u:object_r:admin_home_t:s0", "size": 6, "state": "directory", "uid": 0 }172.16.11.101 | success >> {"changed": true, "gid": 0, "group": "root", "mode": "0755", "owner": "root", "path": "/root/ansi", "secontext": "unconfined_u:object_r:admin_home_t:s0", "size": 6, "state": "directory", "uid": 0 }# 172.16.11.101[root@husa ~]# ll 總用量 8 -rw-------. 1 root root 1998 1月 30 02:49 anaconda-ks.cfg drwxr-xr-x. 2 root root 6 1月 31 08:11 ansi -rw-r--r--. 1 root root 708 1月 31 03:39 httpd.csryum
Installs, upgrade, removes, and lists packages and groups with the yum package manager.
-a 'name= conf_file= state={present|latest|absent} enablerepo= disablerepo=' [root@localhost ~]# ansible all -m yum -a 'name=httpd state=present' 172.16.11.101 | success >> {"changed": false, "msg": "", "rc": 0, "results": ["httpd-2.4.6-31.el7.centos.x86_64 providing httpd is already installed"] }172.16.11.102 | success >> {"changed": false, "msg": "", "rc": 0, "results": ["httpd-2.4.6-31.el7.centos.x86_64 providing httpd is already installed"] } # 安裝httpd,但是提示已經(jīng)早已安裝過(guò)了copy
The copy module copies a file on the local box to remote locations. Use the fetch module to copy files from remote locations to the local box. If you need variable interpolation in copied files, use the template module.把本地主機(jī)的文件復(fù)制到遠(yuǎn)程主機(jī)
-a 'dest= src= content= owner= group= mode=' [root@localhost ~]# ansible all -m copy -a 'src=/etc/httpd/conf/httpd.conf dest=/tmp mode=744 owner=root group=root' 172.16.11.101 | success >> {"changed": true, "checksum": "fa2850bb3dae846b727917ae0777bc85109cf4e0", "dest": "/tmp/httpd.conf", "gid": 0, "group": "root", "md5sum": "f6351c6d8c8dfc5899820d8c46d74651", "mode": "0744", "owner": "root", "secontext": "unconfined_u:object_r:admin_home_t:s0", "size": 34419, "src": "/root/.ansible/tmp/ansible-tmp-1451141734.1-70247620035515/source", "state": "file", "uid": 0 }172.16.11.102 | success >> {"changed": true, "checksum": "fa2850bb3dae846b727917ae0777bc85109cf4e0", "dest": "/tmp/httpd.conf", "gid": 0, "group": "root", "md5sum": "f6351c6d8c8dfc5899820d8c46d74651", "mode": "0744", "owner": "root", "secontext": "unconfined_u:object_r:admin_home_t:s0", "size": 34419, "src": "/root/.ansible/tmp/ansible-tmp-1451141734.12-232176586930023/source", "state": "file", "uid": 0 }# remote location[root@husa ~]# ll /tmp 總用量 60 drwxr-xr-x. 2 root root 17 1月 30 02:40 hsperfdata_root -rwxr--r--. 1 root root 34419 1月 31 08:29 httpd.confservice
Controls services on remote hosts. Supported init systems include BSD init, OpenRC, SysV, Solaris SMF, systemd, upstart.
-a 'name= state={started|stopped|restarted} enabled= runlevel=' enabled表示開(kāi)機(jī)自啟 # 啟動(dòng)httpd服務(wù)并設(shè)置開(kāi)機(jī)啟動(dòng)[root@localhost ~]# ansible all -m service -a 'name=httpd state=started enabled=true' 172.16.11.102 | success >> {"changed": true, "enabled": true, "name": "httpd", "state": "started" }172.16.11.101 | success >> {"changed": true, "enabled": true, "name": "httpd", "state": "started" }shell
The shell module takes the command name followed by a list of space-delimited arguments. It is almost exactly like the command module but runs the command through a shell (/bin/sh) on the remote node.可以使用管道重定向等
-a 'COMMAND' # 向遠(yuǎn)程主機(jī)的centos用戶設(shè)置密碼為root[root@localhost ~]# ansible all -m shell -a 'echo "root" | passwd --stdin centos' 172.16.11.101 | success | rc=0 >> Changing password for user centos. passwd: all authentication tokens updated successfully.172.16.11.102 | success | rc=0 >> Changing password for user centos. passwd: all authentication tokens updated successfully.script
The script module takes the script name followed by a list of space-delimited arguments. The local script at path will be transferred to the remote node and then executed. The given script will be processed through the shell environment on the remote node. This module does not require python on the remote system, much like the raw module.把本地的腳本文件傳遞到遠(yuǎn)程主機(jī)并執(zhí)行,執(zhí)行結(jié)果
-a '/PATH/TO/SCRIPT' # local host[root@localhost ~]# vim hello.sh#!/bin/bash #echo "hello $HOSTNAME"[root@localhost ~]# ansible all -m script -a '/root/hello.sh' 172.16.11.101 | success >> {"changed": true, "rc": 0, "stderr": "OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug1: mux_client_request_session: master session id: 2\r\nShared connection to 172.16.11.101 closed.\r\n", "stdout": "hello husa\r\n" }172.16.11.102 | success >> {"changed": true, "rc": 0, "stderr": "OpenSSH_5.3p1, OpenSSL 1.0.1e-fips 11 Feb 2013\ndebug1: Reading configuration data /etc/ssh/ssh_config\r\ndebug1: Applying options for *\r\ndebug1: auto-mux: Trying existing master\r\ndebug1: mux_client_request_session: master session id: 2\r\ndebug1: mux_client_request_session: master session id: 2\r\nShared connection to 172.16.11.102 closed.\r\n", "stdout": "hello localhost.localdomain\r\n" }script上傳到遠(yuǎn)程主機(jī)并在遠(yuǎn)程主機(jī)執(zhí)行,結(jié)果在本地主機(jī)可以捕獲
cron
Use this module to manage crontab entries. This module allows you to create named crontab entries, update, or delete them. The module includes one line with the description of the crontab entry “#Ansible: ” corresponding to the “name” passed to the module, which is used by future ansible/module calls to find/check the state. The “name” parameter should be unique, and changing the “name” value will result in a new cron task being created (or a different one being removed)
-a 'name= state= minute= hour= day= month= weekday= job='setup
This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks. It can also be executed directly by /usr/bin/ansible to check what variables are available to a host. Ansible provides many facts about the system, automatically. 獲取指定主機(jī)的facts
[root@localhost ~]# ansible 172.16.11.101 -m setup 172.16.11.101 | success >> {"ansible_facts": {"ansible_all_ipv4_addresses": ["192.168.200.101", "172.16.11.101"], "ansible_all_ipv6_addresses": ["fe80::20c:29ff:fecc:de26", "fe80::20c:29ff:fecc:de1c"], "ansible_architecture": "x86_64", "ansible_bios_date": "07/02/2015", "ansible_bios_version": "6.00", "ansible_cmdline": {"BOOT_IMAGE": "/vmlinuz-3.10.0-229.el7.x86_64", "LANG": "zh_CN.UTF-8", "crashkernel": "auto", "quiet": true, "rhgb": true, "ro": true, "root": "UUID=6db0652d-dad9-400a-bd91-0d6dfb59b2b4"}, "ansible_date_time": {"date": "2016-01-31", "day": "31", "epoch": "1454201429", "hour": "08", "iso8601": "2016-01-31T00:50:29Z", "iso8601_micro": "2016-01-31T00:50:29.107179Z", "minute": "50", "month": "01", "second": "29", "time": "08:50:29", "tz": "CST", "tz_offset": "+0800", "weekday": "Sunday", "year": "2016"}, "ansible_default_ipv4": { ......templates
-a 'dest= src= content= owner= group= mode='playbooks
contain one or more plays written in YAML executed in the order it is writtenansible-playbook - run an ansible playbook
ansible-playbook
變量
變量命名:字母數(shù)字下劃線,只能以字母開(kāi)頭變量種類:facts:由遠(yuǎn)程主機(jī)發(fā)回的主機(jī)屬性信息,這些信息被保存在ansible變量中;無(wú)須定義,可直接調(diào)用自定義變量通過(guò)命令行傳遞:ansible-playbook xxx.yml --extra-vars "host=xxx user=xxx"通過(guò)roles傳遞:在roles的yml文件中使用 {{role:role_name,var_name:var_value}},傳遞模板變量的值給變量主機(jī)變量:定義在inventory中的主機(jī)之后的變量組變量:定義在inventory中的組上的變量inventory參數(shù)
ansible基于ssh連接inventory中指定的遠(yuǎn)程主機(jī)時(shí),以此處的參數(shù)指定的屬性進(jìn)行
ansible_ssh_host ansible_ssh_user ansible_ssh_pass ansible_sudo_pass例子:
oot@localhost ~]# vim /etc/ansible/hosts [real server] 172.16.11.101 ansible_ssh_user='root' ansible_ssh_port=22 ansible_ssh_pass='root' ansible_sudo_pass='xxxx' 172.16.11.102facts
使用setup模塊可以查看遠(yuǎn)程主機(jī)的各種facts
主機(jī)變量
定義在inventory中的主機(jī)之后的變量
[root@localhost ~]# vim /etc/ansible/hosts [real server:vars] 172.16.11.101 user=apace group=apace 172.16.11.102自定義變量之通過(guò)命令行傳遞
ansible-playbook test.yml --extra-vars "host=172.16.11.101" #這里的host就是一個(gè)通過(guò)命令行傳遞的自定義變量組變量
[root@localhost ~]# vim /etc/ansible/hosts [real server:vars] user=apache group=apache 172.16.11.101 172.16.11.102palybook結(jié)構(gòu)
host {hostname|inventory_name|ip} #表示遠(yuǎn)程主機(jī)標(biāo)識(shí)
remote_user:remote_user_name #表示遠(yuǎn)程主機(jī)上執(zhí)行任務(wù)的身份
vars: #定義變量
Key1:Value1 #這種變量的應(yīng)用方法為 {{Keyx}}
Key2:Value2
Keyn:Valuen
tasks: #表示一個(gè)任務(wù)組,用列表表示- name:task_name1 #具有標(biāo)識(shí)性質(zhì)的字符串比如:task useradd
module_name:module_args #比如:user:name={{var_name}} state=present或者user:name=username state=present,args中的變量還可以是item中的
when:condition #比如條件為facts即:ansible_os_family==”RedHat”
notify:handlers_name #表示發(fā)生改變才觸發(fā)的任務(wù),handlers_name表示handlers條目中的名稱
with_items: - item_name1 #這種形式的item在args中使用 {{item}} 應(yīng)用
- item_name2
- item_namen
- {var_name:’content’,var_name2:’content’,var_namen:’content’} #這種形式的item在args中使用 {{item.var_name}} 應(yīng)用
- {var_name:’content’,var_name2:’content’,var_namen:’content’}
template:template_args #這里顯示使用template模塊,其參數(shù)主要是 src 和 dest,一般用于配置文件的修改使用,src的配置文件應(yīng)該使用jinja2模板的語(yǔ)法,使用{{tempalte_name}}定義,而其應(yīng)用可以使用主機(jī)變量、自定義變量和vars變量
tags:tags_name #定義tasks的TAGS,這個(gè)tags可用于ansible-playbook -t tags_name playname.yml來(lái)調(diào)用特定的tasks - name:task_namex… #表示可以定義多個(gè)tasks
handlers: name:handlers_name1
module_name:module_args #表示handlers同樣也使用模塊來(lái)定義任務(wù)name:handlers_name2… #表示可以定義多個(gè)handlers
- name:task_name1 #具有標(biāo)識(shí)性質(zhì)的字符串比如:task useradd
roles
在roles目錄中定義各種元素,然后再定義一個(gè)playbook,在playbook中定義好role的名稱,執(zhí)行這個(gè)yml文件,就能夠按照目錄結(jié)構(gòu)尋找相應(yīng)的配置
文件組織格式
一個(gè)目錄表示一個(gè)roles,roles下的目錄是各種配置
roles用于實(shí)現(xiàn)“代碼復(fù)用”;
roles以特定的層次型格式組織起來(lái)的playbook元素(variables, tasks, templates, handlers);可被playbook以role的名字直接進(jìn)行調(diào)用;
安裝ansible
ansible在epel源,要先配置好epel源
[root@localhost ~]# yum install ansible Installing:ansible noarch 1.9.2-1.el6 epel 1.7 MTransaction Summary Installed:ansible.noarch 0:1.9.2-1.el6 Complete!配置host inventory文件
[root@localhost ~]# vim /etc/ansible/hosts # This is the default ansible 'hosts' file. # # It should live in /etc/ansible/hosts # # - Comments begin with the '#' character # - Blank lines are ignored # - Groups of hosts are delimited by [header] elements # - You can enter hostnames or ip addresses # - A hostname/ip can be a member of multiple groups [real server] 172.16.11.101 172.16.11.102上面就把172.16.11.101和172.16.11.102作為了ansible得被管理主機(jī)
另外可以使用ansible -i PATH,–inventory=PATH指明使用的host inventory文件路徑
基于密鑰認(rèn)證
# ansible所在主機(jī) [root@localhost .ssh]# ssh-keygen -b 2048 Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: 35:e3:89:d5:d8:94:99:96:c4:6b:a1:b7:e6:64:fa:9b root@localhost.localdomain The key's randomart image is: +--[ RSA 2048]----+ | oo= | | =O | | *ooo | | =.++ | | S oo . | | = | | * | | . .. | | .E. | +-----------------+# 被管理主機(jī)[root@localhost .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.11.101 The authenticity of host '172.16.11.101 (172.16.11.101)' can't be established. RSA key fingerprint is 7c:83:16:24:34:09:db:58:a5:31:32:1b:c9:25:07:a2. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '172.16.11.101' (RSA) to the list of known hosts. root@172.16.11.101's password: Now try logging into the machine, with "ssh 'root@172.16.11.101'", and check in:.ssh/authorized_keysto make sure we haven't added extra keys that you weren't expecting.# 被管理主機(jī)的.ssh目錄下生成了authorized_keys文件說(shuō)明OK [root@husa .ssh]# cd [root@husa ~]# ls ~/.ssh/ authorized_keys# 同樣的方法把a(bǔ)nsible所在主機(jī)的公鑰復(fù)制到RS2[root@localhost .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@172.16.11.102 The authenticity of host '172.16.11.102 (172.16.11.102)' can't be established. RSA key fingerprint is fe:1e:4a:0d:c9:d1:67:91:57:1f:01:2c:ea:c1:b3:69. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '172.16.11.102' (RSA) to the list of known hosts. root@172.16.11.102's password: Now try logging into the machine, with "ssh 'root@172.16.11.102'", and check in:.ssh/authorized_keysto make sure we haven't added extra keys that you weren't expecting.簡(jiǎn)單使用ansible
[root@localhost .ssh]# ansible-doc -s ping less 436 Copyright (C) 1984-2009 Mark Nudelmanless comes with NO WARRANTY, to the extent permitted by law. For information about the terms of redistribution, see the file named README in the less distribution. Homepage: http://www.greenwoodsoftware.com/less - name: T r y t o c o n n e c t t o h o s t a n d r e t u r n action: ping (END) [root@localhost .ssh]# ansible all -m ping 172.16.11.101 | success >> {"changed": false, "ping": "pong" }172.16.11.102 | success >> {"changed": false, "ping": "pong" }# 下面使用的組名也可以 [root@localhost .ssh]# ansible real\ server -m ping 172.16.11.101 | success >> {"changed": false, "ping": "pong" }172.16.11.102 | success >> {"changed": false, "ping": "pong" }# 下面是在RS上的抓包信息 [root@husa ~]# tcpdump -i eno16777728 icmp tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eno16777728, link-type EN10MB (Ethernet), capture size 65535 bytes 06:58:04.918637 IP 172.16.250.90 > 172.16.250.35: ICMP redirect 172.16.11.207 to net 172.16.11.207, length 144 06:58:05.941705 IP 172.16.250.90 > 172.16.250.35: ICMP redirect 172.16.11.207 to net 172.16.11.207, length 144 06:58:07.062513 IP 172.16.250.90 > 172.16.250.35: ICMP redirect 172.16.11.207 to net 172.16.11.207, length 144 06:58:09.036487 IP 172.16.250.90 > 172.16.250.35: ICMP redirect 172.16.11.207 to net 172.16.11.207, length 48使用ansible-doc -s查看模塊的用法,使用ansible hosts -m module -a發(fā)送命令
參考文獻(xiàn):http://chrisrc.me/2015-09-23/autoit-ansible/
http://afoo.me/posts/2014-06-12-understanding-ansible.html#fnref2
總結(jié)
以上是生活随笔為你收集整理的Operations-ansible-01的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: BERT模型—2.BERT模型预训练与微
- 下一篇: MySQL中rank函数的使用