ansible格式:html
ansible <host-pattern> [-f forks] [-m module_name] [-a args]node
args: 用法python
key=value 好比調用user模塊時,name=dongshi或者state=presentlinux
# ansible all -m cron -a 'name="sync time from ntpserver" minute="*/10" job="/sbin/ntpdate -u pool.ntp.org &> /dev/null"'nginx
# ansible all -m cron -a "name='sync time from ntpserver' minute='*/10' job='/sbin/ntpdate -u 133.100.11.8 &> /dev/null'"git
# ansible all -a '/sbin/ntpdate -u pool.ntp.org'github
# ansible all -m cron -a 'name="sync time from ntpserver" state=absent' //刪除任務時只需指定任務的name,和跟state=absentweb
//注意上面二者的單雙引號的引用,-a後面若是先用'',那麼裏面的name="sync time from ntpserver"就要用雙引號,可互換,但不能混用。shell
//多個key=value之間要用空格隔開,state若是省略,就是默認的present,若是不指明user,默認就是管理員apache
# crontab -l 時間同步IP地址:https://www.cnblogs.com/xxlu/archive/2017/06/09/6965548.html
#Ansible: sync time from ntpserver
*/10 * * * * /sbin/ntpdate -u pool.ntp.org &> /dev/null
注意:command模塊要執行命令無須爲key=value格式,而是直接給出要執行的命令便可;
安裝epel源
# yum install epel-release
# yum repolist
# ansible websrvs -a 'wget -O /tmp/ansible.rpm http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm'
//下載文件,首先必須指明下面文件保存的路徑已經文件明:/tmp/ansible.rpm,另外就是被管控主機要安裝了所調用的命令,這裏142和143要安裝wget命令。
//wegt可使用靜默模式
192.168.184.143 | FAILED | rc=2 >> //143沒有安裝wget命令 [Errno 2] No such file or directory 192.168.184.142 | SUCCESS | rc=0 >> //142安裝了wget命令 --2018-12-30 11:54:30-- http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm Resolving dl.fedoraproject.org (dl.fedoraproject.org)... 209.132.181.23, 209.132.181.24 Connecting to dl.fedoraproject.org (dl.fedoraproject.org)|209.132.181.23|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 15080 (15K) [application/x-rpm] Saving to: ‘/tmp/ansible.rpm’ 0K .......... .... 100% 77.3K=0.2s 2018-12-30 11:54:31 (77.3 KB/s) - ‘/tmp/ansible.rpm’ saved [15080/15080]
# ansible websrvs -a 'yum install -y wget' //批量安裝wegt
192.168.184.142 | SUCCESS | rc=0 >> //以前被管控142主機已經安裝了wget Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirrors.neusoft.edu.cn * extras: mirrors.tuna.tsinghua.edu.cn * updates: mirrors.neusoft.edu.cn Package wget-1.14-18.el7.x86_64 already installed and latest version Nothing to do 192.168.184.143 | SUCCESS | rc=0 >> //被管控主機143以前並無安裝,因此這裏安裝成功 Loaded plugins: fastestmirror Determining fastest mirrors * base: mirrors.neusoft.edu.cn * epel: mirrors.tuna.tsinghua.edu.cn * extras: mirrors.tuna.tsinghua.edu.cn * updates: mirrors.tuna.tsinghua.edu.cn Resolving Dependencies --> Running transaction check ---> Package wget.x86_64 0:1.14-18.el7 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: wget x86_64 1.14-18.el7 base 547 k Transaction Summary ================================================================================ Install 1 Package Total download size: 547 k Installed size: 2.0 M Downloading packages: Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : wget-1.14-18.el7.x86_64 1/1 Verifying : wget-1.14-18.el7.x86_64 1/1 Installed: wget.x86_64 0:1.14-18.el7 Complete!
爲websrvs組中的兩臺主機建立一個用戶
# ansible-doc -s user //首先能夠查看user的語法
- name: Manage user accounts user: append: # If `yes', will only add groups, not set them to just the list in `groups'. comment: # Optionally sets the description (aka `GECOS') of user account. createhome: # Unless set to `no', a home directory will be made for the user when the account is created or if the home directory does not exist. expires: # An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently supported on Linux and FreeBSD. force: # When used with `state=absent', behavior is as with `userdel --force'. generate_ssh_key: # Whether to generate a SSH key for the user in question. This will *not* overwrite an existing SSH key. group: # Optionally sets the user's primary group (takes a group name). groups: # Puts the user in list of groups. When set to the empty string ('groups='), the user is removed from all groups except the primary group. Before version 2.3, the only input format allowed was a 'comma separated string', now it should be able to accept YAML lists also. home: # Optionally set the user's home directory. local: # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments 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 for FreeBSD, OpenBSD and NetBSD systems. move_home: # If set to `yes' when used with `home=', attempt to move the user's home directory to the specified directory if it isn't there already. 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. See the user example in the github examples directory for what this looks like in a playbook. See http://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted- passwords-for-the-user-module for details on various ways to generate these password values. Note on Darwin system, this value has to be cleartext. Beware of security issues. remove: # When used with `state=absent', behavior is as with `userdel --remove'. seuser: # Optionally sets the seuser type (user_u) on selinux enabled systems. shell: # Optionally set the user's shell. skeleton: # Optionally set a home skeleton directory. Requires createhome option! ssh_key_bits: # Optionally specify number of bits in SSH key to create. ssh_key_comment: # Optionally define the comment for the SSH key. ssh_key_file: # Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the user's home directory. ssh_key_passphrase: # Set a passphrase for the 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 action if the state is different from what is stated. system: # When creating an account, 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 for newly created users. (END)
# ansible websrvs -m user -a "name=dongshi state=present" //最關鍵的一項就是名稱,state表示狀態,-m user表示調用user模塊
192.168.184.142 | SUCCESS => { "changed": true, "comment": "", "createhome": true, "group": 1000, "home": "/home/dongshi", "name": "dongshi", "shell": "/bin/bash", "state": "present", "system": false, //不是系統用戶 "uid": 1000 } 192.168.184.143 | SUCCESS => { "changed": true, "comment": "", "createhome": true, "group": 1000, "home": "/home/dongshi", "name": "dongshi", "shell": "/bin/bash", "state": "present", "system": false, "uid": 1000 }
# ansible websrvs -m user -a "name=dongshi state=absent remove=yes" //刪除用戶,同時刪除家目錄
192.168.184.143 | SUCCESS => { "changed": true, "force": false, "name": "dongshi", "remove": false, "state": "absent" } 192.168.184.142 | SUCCESS => { "changed": true, "force": false, "name": "dongshi", "remove": false, "state": "absent" }
command
-a 'COMMAND' //-a能夠省略
user
-a 'name= state={present|absent} system= uid='
group
-a 'name= gid= state= system='
cron
-a 'name= minute= hour= day= month= weekday= job= user= state='
copy
-a 'dest= src= mode= owner= group='
# ansible websrvs -m copy -a 'src=/etc/fstab dest=/tmp/fstab.tmp mode=600'
file
-a 'path= mode= owner= group= state={directory|link|present|absent} src='
# ansible websrvs -m file -a 'path=/tmp/dir state=directory'
# ansible websrvs -m file -a 'path=/tmp/fstab.symlink state=link src=/tmp/fstab.tmp'
//建立一個鏈接文件/tmp/fstab.symlink,鏈接目標指向src,若是其中一臺被管控主機沒有鏈接目標的文件即fstab.tmp,那麼就會報錯,也可使用force=yes強制
# ansible all -m file -a 'path=fstab.sym state=link src=/tmp/fstab.tmp force=yes' //在沒有鏈接目標文件的狀況下強制建立
# ansible all -m file -a 'path=fstab.sym state=absent force=yes' //強制刪除連接
ping
沒有參數
# ansible all -m ping
yum
-a 'name= state={present|latest|absent}'
# ansible websrvs -m yum -a 'name=nginx state=latest' //安裝nginx,可是必需要有epel源,這裏同時安裝了centos7和centos6都沒有問題
//若是沒有epel源,可參考https://www.jianshu.com/p/fd9bc81e94ed
# ansible websrvs -m yum -a 'name=nginx state=absent' //卸載nginx
service //管理每個被管控主機上的服務的
-a 'name= state={started|stopped|restarted} enabled='
# ansible websrvs -m service -a 'name=nginx state=started enabled=yes' //同時啓動centos6和centos7主機上的nginx服務
# ansible websrvs -m service -a 'name=nginx state=started enabled=yes' //關閉服務
shell //指明一個shell程序運行後面給出的命令,而不是直接在當前命令中運行
-a 'COMMAND' //無需指明key=value
假如在每個主機上建立一個centos用戶,並添加密碼爲centos
# ansible websrvs -m service -a 'name=nginx state=started enabled=yes' //此時centos用戶建立成功,但忘了加密碼,用command模塊加密碼
# ansible websrvs -m command -a 'echo centos | passwd --stdin centos' //在管控主機上爲centos用戶加密碼
192.168.184.143 | SUCCESS | rc=0 >>
centos | passwd --stdin centos //注意,這裏只是把centos | passwd --stdin centos看成字符串echo出來了而已,並無把"|"理解爲管道去執行
192.168.184.142 | SUCCESS | rc=0 >>
centos | passwd --stdin centos
192.168.184.145 | SUCCESS | rc=0 >>
centos | passwd --stdin centos
# tail -2 /etc/shadow
centos:!!:17896:0:99999:7:::
dongshi:$6$8/UL2igK$fEp5oQTQG4pVkHBuuIkykj5dimzVJBDptOx7kzIXflyXGdUm.sAAZHmZXKbS9UYskiEMNW.Jq7QcL15viv1cQ0:17896:0:99999:7:::
//查看任何一個被管控主機時,centos用戶是沒有密碼的,由於在使用ansible在管控主機上爲被管控主機上的用戶添加密碼時,使用echo命令加管道"|",這時echo命令就在當前主機(管控主機)上執行此命令了,而不是把echo命令送到目標主機上後再執行echo命令的。因此要利用管道作一些複雜命令時,就好比上一個例子,那麼command命令是沒法實現的,若是想把這些命令(即'echo centos | passwd --stdin centos')放在一塊兒執行,那麼須要把這些命令放在shell子進程中實現,這就是shell模塊的意義。
# ansible websrvs -m shell -a 'echo centos | passwd --stdin centos' //調用shell模塊
192.168.184.142 | SUCCESS | rc=0 >>
Changing password for user centos.
passwd: all authentication tokens updated successfully. //這裏才把"|"理解爲管道
192.168.184.143 | SUCCESS | rc=0 >>
Changing password for user centos.
passwd: all authentication tokens updated successfully.
192.168.184.145 | SUCCESS | rc=0 >>
Changing password for user centos.
passwd: all authentication tokens updated successfully.
# tail -2 /etc/shadow //此時centos用戶的密碼纔算添加成功
centos:$6$A2c63GoQ$RTqD0MCCIrvioLQDNs5xc2FQLVdCGuA31H4uu5zTDKWE.lhThdQ43THOhLP3GXrcJmqisUj9WP/ChZ8cTicFn.:17896:0:99999:7:::
dongshi:$6$8/UL2igK$fEp5oQTQG4pVkHBuuIkykj5dimzVJBDptOx7kzIXflyXGdUm.sAAZHmZXKbS9UYskiEMNW.Jq7QcL15viv1cQ0:17896:0:99999:7:::
script //若是本地主機有一個腳本,但這個腳本不想在本地運行,而是在每個遠程主機上運行,就調用script模塊。
//它會先把腳本傳送到目標主機,而後把腳本運行一遍,運行完後再把腳本刪除掉。
# ansible-doc -s script //查看模塊script的詳細信息
-a '/path/to/script' //指明路徑就能夠了,-a能夠省略
實例:在管控主機上建立一個腳本
# vim /tmp/test.sh //注意這裏並無爲test.sh添加執行權限
#!/bin/bash
#
echo "$(hostname) ansible test." > /tmp/ansible.txt
# ansible websrvs -m script -a '/tmp/test.sh' //自動把腳本複製到遠程主機,調用bash shell去執行這個腳本,執行完成後,再把腳本刪除
# cat /tmp/ansible.txt //在遠程主機上查看建立結果
node2 ansible test.
setup - name: Gathers facts about remote hosts 從遠程主機收集facts,包括主機名、IP地址、操做系統版本號、多少顆CPU等物理平臺的相關信息。
在指揮每個被管控主機運行ansible程序時或在ansible的指揮下被管控主機完成某些任務時,每個被管控主機會首先向ansible報告其主機相關信息,或者使用setup去收集,要求被管控主機全部的可收集信息都報告給管控主機,收集來的每個元素和元素的值,每個元素的元素名均可以直接看成變量使用。這些變量一般稱爲facts
# ansible websrvs -m setup | less //因爲信息太多,因此後面加了一個less
好比ansible_architecture是facts的名稱,而x86_64是facts的值,facts的名稱會在被管控主機在被指揮的後,運行的時候都報告給管控主機的,所以能夠在配置文件中直接調用這些變量名來做爲判斷標準。
playbooks的核心元素:
tasks: 任務 playbooks中最核心的元素
variables:變量,有不少種
templates:模板,能夠根據模板建立配置文件的一種方式,好比copy模塊,但copy文件只能原封不動的把文件傳輸到指定主機,若是想根據目標主機當前的實際狀態配置 某些參數的值,就須要藉助於templates機制,經過文件提供的模板來實現
handlers:處理器,主要做用:好比配置文件修改了,那麼就要重啓服務。一旦出現異常情況,如何處理就要經過handlers進行指定
roles:角色
playbooks是如何定義的呢?它依賴於YAML
- name:deploy web server //-:引導一個列表,name、user、sudo和hosts屬於同一個列表中四個key value鍵值對,遵循特定格式
user:foouser
sudo:true
hosts:all
tasks:
name:install apache
apt:pkg=apache2-mpm-prefork state=latest
一、YAML介紹
YAML是一個可讀性高的用來表達資料序列的格式。YAML參考了其餘多種語言,包括:XML、C語言、Python、Perl以及電子郵件格式RFC2822等。
Clark Evans在2001年在首次發表了這種語言,另外Ingy döt Net與Oren Ben-Kiki也是這語言的共同設計者。
YAML Ain't Markup Language,即YAML不是XML。不過,在開發的這種語言時,YAML的意思實際上是:"Yet Another Markup Language"(還是一種標記語言)。
二、YAML的特性:
YAML的可讀性好
YAML和腳本語言的交互性好
YAML使用實現語言的數據類型
YAML有一個一致的信息模型
YAML易於實現
YAML能夠基於流來處理
YAML表達能力強,擴展性好
更多的內容及規範參見http://www.yaml.org。
三、YAML語法
YAML的語法和其餘高階語言相似,而且能夠簡單表達清單、散列表(鍵值)、標量等數據結構。其結構(Structure)經過空格來展現,序列(Sequence)裏的項用"-"來表明,Map裏的鍵值對用":"分隔。
下面是一個示例:
name: John Smith //這是一個鍵值對,即map
age: 41 //這也是一個鍵值對
gender: Male
spouse: //鍵值數據結構是能夠嵌套的,好比spouse是鍵,裏面嵌套的都是值
name: Jane Smith //這是一對鍵值對
age: 37
gender: Female //紅色部分三個都是鍵spouse的值,都叫作映射
children: //children是一個鍵,它的值由一個列表組成,這個列表有兩個元素。若是同一類元素出現2個以上時,使用"-"來引導,這種就叫作列表
- name: Jimmy Smith
age: 17
gender: Male
- name: Jenny Smith
age 13
gender: Female
YAML文件擴展名一般爲.yaml,如example.yaml。
3.1 list
列表的全部元素均使用"-"打頭,列表內部的元素能夠是字符串(- Apple),能夠是鍵值對(- name: Jimmy Smith),也能夠是N個鍵值對組合起來的,是一種擴展或嵌套
例如:
# A list of tasty fruits
- Apple
- Orange
- Strawberry
- Mango
3.2 dictionary 字典,由多個鍵值對共同組成的集合
字典經過key與value進行標識,
例如:
---
# An employee record
name: Example Developer
job: Developer
skill: Elite
也能夠將key:value放置於{}中進行表示,用","進行分割。
例如:
---
# An employee record
{name: Example Developer, job: Developer, skill: Elite}
YAML文件格式介紹
# vim test.yml
tasks: //tasks是鍵,下面三個任務是值。它的值是一個列表,每個列表又是一個字典(這裏的字段有兩個鍵值組成)
- name: install a pkg //第一個任務
yum: name=nginx state=latest
- name: copy conf file //第二個任務
copy: src= dest= state=
- name: start nginx service //第三個任務
service: name= state=
Ansible基礎元素
一、變量
1.1.1 變量命名
變量名僅能由字母、數字和下劃線組成,且只能以字母開頭。
1.1.2 facts
facts是由正在通訊的遠程目標主機發回的信息,這些信息被保存在ansible變量中。要獲取指定的遠程主機所支持的全部facts,可以使用以下命令進行:
# ansible hostname -m setup
1.1.3 register
把任務的輸出定義爲變量,而後用於其餘任務,示例以下:
tasks:
- shell: /usr/bin/foo //把/usr/bin/foo運行的結果保存在register中,而後調用這個register
register: foo_result
ignore_errors: True
1.1.4 經過命令行傳遞變量
在運行playbook的時候也能夠傳遞一些變量供playbook使用,示例以下:
ansible-playbook test.yml --extra-vars "hosts=www user=mageedu"
1.1.5 經過roles傳遞變量
當給一個主機應用角色的時候能夠傳遞變量,而後在角色內使用這些變量,示例以下:
- hosts: webservers
roles:
- commom
- { role: foo_app_instance, dir: '/web/htdocs/a.com', port: 8080 }
1.2 Inventory
ansible的主要功用在於批量主機操做,爲了便捷地使用其中的部分主機,能夠在inventory file中將其分組命名。默認的inventory file爲/etc/ansible/hosts。
inventory file能夠有多個,且也能夠經過Dynamic Inventory來動態生成。
1.2.1 inventory文件格式
inventory文件遵循INI文件風格,中括號中的字符爲組名。能夠將同一個主機同時歸併到多個不一樣的組中;此外,當如若目標主機使用了非默認的SSH端口,還能夠在主機名稱以後使用冒號加端口號來標明。
ntp.magedu.com
[webservers] //組名
www1.magedu.com:2222
www2.magedu.com
[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com
若是主機名稱遵循類似的命名模式,還可使用列表的方式標識各主機,例如:
[webservers] //使用通配符
www[01:50].example.com
[databases] //使用列表
db-[a:f].example.com
1.2.2 主機變量,在inventory中也可使用變量
能夠在inventory中定義主機時爲其添加主機變量以便於在playbook中使用。例如:
hostname name=value name=value
[webservers]
www1.magedu.com http_port=80 maxRequestsPerChild=808 //http_port是變量名,80就是值
www2.magedu.com http_port=8080 maxRequestsPerChild=909 //主機變量的好處是即便變量名同樣,但每個主機均可以有與其餘主機不同的取值
上述是給每一個主機定義變量,即在www1.magedu.com主機上執行時,調用某個模板直接能夠調用http_port變量替換成80即變量值。除此以外還能夠在主機後面定義主機參數,主機參數不是爲了在模板中調用變量的目的,而是連接主機時它的ssh參數。能夠在管控主機和非管控主機之間不作認證,而是在本地文件中指明absible_ssh_host,詳情見1.2.5。
1.2.3 組變量
組變量是指賦予給指定組內全部主機上的在playbooks中可用的變量。例如:
[groupname:vars]
name=value
name=value
[webservers]
www1.magedu.com
www2.magedu.com
[webservers:vars] //這裏的webservers就是上面定義的[webservers]組 ,webservers是組名,可變。:vars是固定格式不能改變,
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com
1.2.4 組嵌套
inventory中,組還能夠包含其它的組,而且也能夠向組中的主機指定變量。不過,這些變量只能在ansible-playbook中使用,而ansible不支持。例如:
[apache]
httpd1.magedu.com
httpd2.magedu.com
[nginx]
ngx1.magedu.com
ngx2.magedu.com
[webservers:children] //webservers表示組名,children表示要調用apache和nginx兩個組,這是固定格式:children是不能變的,webservers即組名可變
apache
nginx
[webservers:vars]
ntp_server=ntp.magedu.com
1.2.5 inventory參數
ansible基於ssh鏈接inventory中指定的遠程主機時,還能夠經過參數指定其交互方式;這些參數以下所示:
ansible_ssh_host //連接的IP
The name of the host to connect to, if different from the alias you wish to give to it.
ansible_ssh_port //連接的端口
The ssh port number, if not 22
ansible_ssh_user //連接的用戶
The default ssh user name to use.
ansible_ssh_pass //連接的密碼
The ssh password to use (this is insecure, we strongly recommend using --ask-pass or SSH keys)
ansible_sudo_pass
The sudo password to use (this is insecure, we strongly recommend using --ask-sudo-pass)
ansible_connection
Connection type of the host. Candidates are local, ssh or paramiko. The default is paramiko before Ansible 1.2, and 'smart' afterwards which detects whether usage of 'ssh' would be feasible based on whether ControlPersist is supported.
ansible_ssh_private_key_file
Private key file used by ssh. Useful if using multiple keys and you don't want to use SSH agent.
ansible_shell_type
The shell type of the target system. By default commands are formatted using 'sh'-style syntax by default. Setting this to 'csh' or 'fish' will cause commands executed on target systems to follow those shell's syntax instead.
ansible_python_interpreter
The target host python path. This is useful for systems with more
than one Python or not located at "/usr/bin/python" such as \*BSD, or where /usr/bin/python
is not a 2.X series Python. We do not use the "/usr/bin/env" mechanism as that requires the remote user's
path to be set right and also assumes the "python" executable is named python, where the executable might
be named something like "python26".
ansible\_\*\_interpreter
Works for anything such as ruby or perl and works just like ansible_python_interpreter.
This replaces shebang of modules which will run on that host.