ansible自动运维
https://juejin.im/post/5b3a074d51882548bc3aa35e
https://baijiahao.baidu.com/s?id=1650879841344431164&wfr=spider&for=pc
配置文件參考
https://www.cnblogs.com/LuisYang/p/5960660.html
playbook詳解:
https://blog.51cto.com/13630803/2154192
兩個核心文件:ansible.cfg和hosts文件,默認都存放在/etc/ansible目錄下。
ansible.cfg:主要設置一些ansible初始化的信息,比如日志存放路徑、模塊、插件等配置信息
hosts:機器清單,進行分組管理
# config file for ansible -- http://ansible.com/ # ==============================================# nearly all parameters can be overridden in ansible-playbook # or with command line flags. ansible will read ANSIBLE_CONFIG, # ansible.cfg in the current working directory, .ansible.cfg in # the home directory or /etc/ansible/ansible.cfg, whichever it # finds first[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 檢查主機密鑰# 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 # 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# Ex 1: Ungrouped hosts, specify before any group headers.green.example.com blue.example.com 192.168.100.1 192.168.100.10# Ex 2: A collection of hosts belonging to the 'webservers' group[webservers] alpha.example.org beta.example.org 192.168.1.100 192.168.1.110# If you have multiple hosts following a pattern you can specify # them like this:www[001:006].example.com# Ex 3: A collection of database servers in the 'dbservers' group[dbservers]db01.intranet.mydomain.net db02.intranet.mydomain.net 10.25.1.56 10.25.1.57# Here's another example of host ranges, this time there are no # leading 0s:db-[99:101]-node.example.comhttp://www.ansible.com.cn/docs/intro_configuration.html#environmental-configuration
問題1
fatal: [172.18.175.149]: FAILED! => {"msg": "to use the 'ssh' connection type with passwords, you must install the sshpass program"}id_rsa.pub路徑:cat ~/.ssh/id_rsa.pub
在配置了ssh免密認證id_rsa.pub之后,在cmd終端可以實現免密登陸對應配置了密鑰的服務器,但是在python程序中,想要調用cmd執行免密操作,還需要安裝sshpass,sshpass用于非交互式的ssh密碼驗證
沒有sshpass報錯:to use the ‘ssh’ connection type with passwords, you must install the sshpass program
安裝完ansible之后,使用的時候發生如下錯誤:
ansible 192.168.1.2 -i ./hosts -m shell -a “date”
192.168.1.2 | FAILED => to use the ‘ssh’ connection type with passwords, you must install the sshpass program
1
2
只需要安裝sshpass即可,CentOS系統的默認yum源里面并沒有這個軟件,網上有資料說搜狐的yum源里面有,有需要的讀者可以自行查閱。
這里給出sshpass的源碼安裝方式:
$ wget http://sourceforge.net/projects/sshpass/files/latest/download -O sshpass.tar.gz $ tar -xvf sshpass.tar.gz $ cd sshpass-1.06 $ ./configure $ sudo make install問題2
攜帶密碼訪問:
https://www.cnblogs.com/kaishirenshi/p/9466666.html
playbook-劇本 介紹
playbooks是 一個不同于使用Ansible命令行執行方式的模式,其功能更強大靈活。簡單來說,playbook是一個非常簡單的配置管理和多主機部署系統,不同于任何已經存在的模式,可作為一個適合部署復雜應用程序的基礎。Playbook可以定制配置,可以按照指定的操作步驟有序執行,支持同步和異步方式。值得注意的是playbook是通過YAML格式來進行描述定義的。
- 核心元素
Tasks:任務,由模板定義的操作列表
Variables:變量
Templates:模板,即使用模板語法的文件
Handlers:處理器 ,當某條件滿足時,觸發執行的操作
Roles:角色
-
hosts和users介紹
-
在playbook中的每一個play都可以選擇在哪些服務器和以什么用戶完成,hosts一行可以是一個主機組、主機、多個主機,中間以冒號分隔,可使用通配模式。其中remote_user表示執行的用戶賬號。
--- - hosts: abc #指定主機組,可以是一個或多個組。remote_user: root #指定遠程主機執行的用戶名 -
指定遠程主機sudo切換用
# vim ping.yml --- - hosts: abcremote_user: root become: yes #2.6版本以后的參數,之前是sudo,意思為切換用戶運行become_user: mysql #指定sudo用戶為mysql執行playbook # ansible-playbook ping.yml -K
- Tasks list 和action介紹
1:Play的主體部分是task列表,task列表中的各任務按次序逐個在hosts中指定的主機上執行,即在所有主機上完成第一個任務后再開始第二個任務。
在運行playbook時(從上到下執行),如果一個host執行task失敗,整個tasks都會回滾,請修正playbook 中的錯誤,然后重新執行即可。
Task的目的是使用指定的參數執行模塊,而在模塊參數中可以使用變量,模塊執行時冪等的,這意味著多次執行是安全的,因為其結果一致。
2:每一個task必須有一個名稱name,這樣在運行playbook時,從其輸出的任務執行信息中可以很好的辨別出是屬于哪一個task的。如果沒有定義name,‘action’的值將會用作輸出信息中標記特定的task。
3:定義一個task,常見的格式:”module: options” 例如:yum: name=httpd
4:ansible的自帶模塊中,command模塊和shell模塊無需使用key=value格式
-
常用命令
-
ansible-playbook [yaml文件名、也可以yml結尾]
-
例如:ansible-playbook a.yml
-
參數:
-k(–ask-pass) 用來交互輸入ssh密碼
# ansible-playbook a.yml --syntax-check #檢查yaml文件的語法是否正確# ansible-playbook a.yml --list-task #檢查tasks任務# ansible-playbook a.yml --list-hosts #檢查生效的主機# ansible-playbook a.yml --start-at-task='Copy Nginx.conf' #指定從某個task開始運行
-K(-ask-become-pass) 用來交互輸入sudo密碼
-u 指定用戶 -
示例
# vim a.yml --- - hosts: 192.168.200.129 //指定主機remote_user: root //指定在被管理的主機上執行任務的用戶tasks: //任務列表↓- name: disable selinux //任務名關閉防火墻command: '/sbin/setenforce 0' //調用command模塊 執行關閉防火墻命令- name: start httpd //任務名 開啟httpdservice: name=httpd state=started //調用service模塊 開啟httpd 服務 # ansible-playbook a.yml --syntax-check #檢查yaml文件的語法是否正確 # ansible-playbook a.yml
- play中只要執行命令的返回值不為0,就會報錯,tasks停止,可以添加下面
- ignore_errors: True #忽略錯誤,強制返回成功
- Handlers介紹
- andlers也是一些task的列表,和一般的task并沒有什么區別。
- 是由通知者進行的notify,如果沒有被notify,則Handlers不會執行,假如被notify了,則Handlers被執行
- 不管有多少個通知者進行了notify,等到play中的所有task執行完成之后,handlers也只會被執行一次
- 示例
- 引用變量
- 使用:vars: 添加變量
- 直接引用Ansible變量
- ansible_all_ipv4_addresses 獲取IP
-
引用主機變量
-
在組的主機后面添加變量
# vim /etc/ansible/hosts # vim c.yml # ansible-playbook c.yml //執行這個劇本
- 引用文件或key=value變量
ansible-playbook -e key=value或 ansible-playbook -e @[values.yaml],文件要加@
- 查看這個生成的文件
條件判斷
- when的值是一個條件表達式,如果條件判斷成立,這個task就執行,如果判斷不成立,則task不執行
- 如果需要根據變量、facts(setup)或此前任務的執行結果來作為某task執行與否的前提時要用到條件測試,在Playbook中條件測試使用when子句。
- 在task后添加when子句即可使用條件測試:when子句支持jinjia2表達式或語法,例如:
- 多條件判斷
- 組條件判斷
- 自定義條件判斷
- 迭代
- 有需要重復性執行的任務時,可以使用迭代機制。其使用格式為將需要迭代的內容定義為item變量引用,并通過with_items語句指明迭代的元素列表即可。
- 示例:
-
Templates介紹
-
Jinja是基于Python的模板引擎。template類是Jinja的另一個重要組件,可以看作一個編譯過的模塊文件,用來生產目標文本,傳遞Python的變量給模板去替換模板中的標記。
# scp root@192.168.175.130:/etc/httpd/conf/httpd.conf ./templates //復制被管理端的配置文件到本地 # vim templates/httpd.conf //在管理端講配置文件要修改的地方定義變量 Listen {{http_port}} ServerName {{server_name}} MaxClients {{access_num}} -
在/etc/ansible/hosts 添加變量
# vim /etc/ansible/hosts [abc] 192.168.200.129 http_port=192.168.200.129:80 access_num=100 server_name="www.yun.com:80" # vim apache.yml # ansible-playbook apache.yml #然后執行腳本 然后去abc組的主機上查看下配置文件是否已經改了
- Tags介紹
- 在一個playbook中,我們一般會定義很多個task,如果我們只想執行其中的某一個task或多個task時就可以使用tags標簽功能了
-
事實上,不光可以為單個或多個task指定同一個tags。playbook還提供了一個特殊的tags為always。作用就是當使用always當tags的task時,無論執行哪一個tags時,定義有always的tags都會執行。
執行下面命令
# ansible-playbook hosts.yml --tags="only" //去被管理主機上查看文件創建情況 2個tags都會執行
總結
以上是生活随笔為你收集整理的ansible自动运维的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 签名文件
- 下一篇: 深度理解Powell优化算法