1. 程式人生 > 其它 >ansible常用模組使用方法

ansible常用模組使用方法

技術標籤:linuxshell運維

ansible-playbook執行方法

#這個是你選擇的主機
- hosts: webservers
#這個是變數
  vars:
    http_port: 80
    max_clients: 200
#遠端的執行許可權
  remote_user: root
  tasks:
  
如果有些系統做了相關的sudo限制,需要在playbooks裡面開啟sodu,或者直接偷懶,許可權直接為root !
- hosts: web
  remote_user: xiaorui
  tasks:
    - service: name=nginx state=started
      sudo: yes        #是否提權  預設sudo為root
sudo_user:root ####sudo提權為root使用者 #執行劇本,playbook裡面定義過變數,可以使用-e指定變數覆蓋檔案內的變數,-e優先順序最高 ansible-playbook diskpart.yaml [-e disk=/dev/sdb diskfullpath=/dev/sdb1 mountDir=da ansible-playbook #使用方法 ansible-playbook 檔名.yml --syntax-check ##檢查playbook檔案的語法是否正確 ansible-playbook 檔名.yml #執行
#如果過程有報錯想要執行 其中的一個步驟 可以根據tags標籤來進行單獨執行命令: 語法:ansible-playbook --tags="標籤名" 檔名.yml 舉例: ansible-playbook --tags="link" 檔名.yml #執行上面的軟連線部分 13.absible test -m script -a 'test.sh' : 將本地的tesh.sh在遠端主機上執行(指令碼所在路徑只能使用相對路徑) 11.ansible all -m set up : 檢視遠端主機的資訊 12.ansible all -m service -
a 'name=httpd enabled=yes':設定服務是否開機啟動 name=:服務名稱,如httpd 通過命令列指定變數,優先順序最高 ansible-playbook –e varname=value ansible test -m shell -a 'echo Xyd#0918!w|passwd --stdin user1' #修改密碼 修改之後最好確認一下 最好使用script指令碼方式修改 #此方法不保險

YUM模組(yum)

- name: Download the nginx package but do not install it   #下載nginx包但不安裝
  yum:					 	#YUM模組
    name:
      - nginx				#安裝包名稱
    state: latest
    download_only: true           ##只下載包不安裝
    
    
- name: Install a list of packages  #安裝多個數據包
  yum:
    name:
      - nginx
      - php
      - mysql
    state: present  
    
- name: install nginx rpm from a local file    ##安裝本地rpm包檔案
  yum:
    name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
    state: present
    
- name: ensure a list of packages installed   ##嵌入變數 下載安裝包列表
  yum:
    name: "{{ packages }}"
  vars:
    packages:
    - httpd
    - httpd-tools

- name: remove the Apache package       ### state 為absent  解除安裝httpd軟體包
  yum:
    name: httpd
    state: absent


USER 使用者模組(user)

groups:指定使用者的屬組
uid:指定用的uid
password:為使用者設定登陸密碼,此密碼是明文密碼加密後的密碼
update_password:always/on_create
    always:只有當密碼不相同時才會更新密碼(預設)
    on_create:只為新使用者設定密碼
name:指定使用者名稱
createhome:是否建立家目錄 yes|no(預設是yes)
system:是否為系統使用者
remove:當state=absent時,remove=yes則表示連同家目錄一起刪除,等價於userdel -r(預設是no)
state:是建立還是刪除 present(新增(預設值))or absent(移除)
shell:指定使用者的shell環境
append:yes/no
    yes:增量新增group
    no:全量變更group,只設置groups指定的group(預設)
expires:設定使用者的過期時間,值是一個時間戳

    3、注意事項
  注:指定password引數時,不能使用後面這一串密碼會被直接傳送到被管理主機的/etc/shadow檔案中,所以需要先將密碼字串進行加密處理。然後將得到的字串放到password中即可。
- user: name=johnd comment="John Doe" uid=1040 group=admin
- user: name=james shell=/bin/bash groups=admins,developers append=yes
- user: name=johnd state=absent remove=yes
- user: name=james18 shell=/bin/zsh groups=developers expires=1422403387
#生成金鑰時,只會生成公鑰檔案和私鑰檔案,和直接使用ssh-keygen指令效果相同,不會生成authorized_keys檔案。
- user: name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa


       - name: "add user docker"
         user: name={{ item.name }} password={{ item.dockerpass | password_hash('sha512') }} state=present  update_password=always          ##密碼需要加密 不然執行報警告 。不加密也可以執行  沒有查是版本還是其他問題
         with_items:
         - { name: 'docker', dockerpass: '123123' }     
         tags:
         - add user docker
         
         
         # 刪除使用者'
         user:
            name: johnd
            state: absent
            remove: yes
            
         #更新使用者密碼
         user: name={{ item.name }} password={{ item.rootpass | password_hash('sha512') }} state=present  update_password=always 
         with_items:
         - { name: 'root', rootpass: '123123' }     
         tags:
         - update passwd
            
建立三個使用者
    - name: create user
      user: name={{item}} 
      with_items:
        - xixi
        - haha
        - memeda

FILE模組檔案(file)

# touch檔案,但新增/刪除一些許可權
- file:
    path: /etc/foo.conf
    state: touch
    mode: "u+rw,g-wx,o-rwx"	  #選項: file, link, directory, hard, touch, absent
##類似同上 稍微有點區別
# touch a file, using symbolic modes to set the permissions (equivalent to 0644)
- file:
    path: /etc/foo.conf
    state: touch
    mode: "u=rw,g=r,o=r"


# 更改檔案所有權、組和模式。使用八進位制數指定模式時,第一個數字應始終為0
- file:
    path: /etc/foo.conf
    owner: foo
    group: foo
    mode: 0644
# 使用file模組建立軟連線
 - file:
    src: /file/to/link/to
    dest: /path/to/symlink
    owner: foo
    group: foo
    state: link
# 建立目錄並賦予755許可權
- file:
    path: /etc/some_directory
    state: directory
    mode: 0755


SERVICE服務模組(service)

#觸發重啟伺服器
    notify:
    - restart apache          ##  handlers -name引用名
  - name: ensure apache is running
    service: name=httpd state=started
#這裡的restart apache 和上面的觸發是配對的。這就是handlers的作用。相當於tag
  handlers:
    - name: restart apache    ##   notify:引用名
      service: name=httpd state=restarted

# 如果httpd沒有啟動 就啟動httpd服務
- service:
    name: httpd
    state: started           #引數可選( started, stopped, restarted, reloaded )
    enabled: yes  #開機啟動     引數可選( yes,no )

#如果httpd啟動 就關閉httpd服務
- service:
    name: httpd
    state: stopped

#重啟網路網絡卡
# Example action to restart network service for interface eth0
- service:
    name: network
    state: restarted
    args: eth0      #注意網絡卡介面名


#可以使用
# Example action to start service foo, based on running process /usr/bin/foo
- service:
    name: foo
    pattern: /usr/bin/foo
    state: started

LINEINFILE檔案修改模組(lineinfile)

path引數 :必須引數,指定要操作的檔案。

line引數 : 使用此引數指定文字內容。

backup引數:是否在修改檔案之前對檔案進行備份。

create引數 :當要操作的檔案並不存在時,是否建立對應的檔案。

regexp引數 :使用正則表示式匹配對應的行,當替換文字時,如果有多行文字都能被匹配,則只有最後面被匹配到的那行文字才會被替換,當刪除文字時,如果有多行文字都能被匹配,這麼這些行都會被刪除。

state引數:當想要刪除對應的文字時,需要將state引數的值設定為absent,absent為缺席之意,表示刪除,state的預設值為present。

backrefs引數:預設情況下,當根據正則替換文字時,即使regexp引數中的正則存在分組,在line引數中也不能對正則中的分組進行引用,除非將backrefs引數的值設定為yes。backrefs=yes表示開啟後向引用,這樣,line引數中就能對regexp引數中的分組進行後向引用了,這樣說不太容易明白,可以參考後面的示例命令理解。backrefs=yes除了能夠開啟後向引用功能,還有另一個作用,預設情況下,當使用正則表示式替換對應行時,如果正則沒有匹配到任何的行,那麼line對應的內容會被插入到文字的末尾,不過,如果使用了backrefs=yes,情況就不一樣了,當使用正則表示式替換對應行時,同時設定了backrefs=yes,那麼當正則沒有匹配到任何的行時,則不會對檔案進行任何操作,相當於保持原檔案不變。

insertafter引數:藉助insertafter引數可以將文字插入到“指定的行”之後,insertafter引數的值可以設定為EOF或者正則表示式,EOF為End Of File之意,表示插入到文件的末尾,預設情況下insertafter的值為EOF,如果將insertafter的值設定為正則表示式,表示將文字插入到匹配到正則的行之後,如果正則沒有匹配到任何行,則插入到檔案末尾,當使用backrefs引數時,此引數會被忽略。

insertbefore引數:藉助insertbefore引數可以將文字插入到“指定的行”之前,insertbefore引數的值可以設定為BOF或者正則表示式,BOF為Begin Of File之意,表示插入到文件的開頭,如果將insertbefore的值設定為正則表示式,表示將文字插入到匹配到正則的行之前,如果正則沒有匹配到任何行,則插入到檔案末尾,當使用backrefs引數時,此引數會被忽略。


# 替換config檔案中匹配到的SELINUX=開頭的行替換為SELINUX=enforcing'
- lineinfile:
    path: /etc/selinux/config
    regexp: '^SELINUX='
    line: 'SELINUX=enforcing'
#刪除/etc/sudoers檔案%wheel開頭的行
- lineinfile:
    path: /etc/sudoers
    state: absent
    regexp: '^%wheel'
#替換行,並指定使用者,組,許可權。
- lineinfile:
    path: /etc/hosts
    regexp: '^127\.0\.0\.1'
    line: '127.0.0.1 localhost'
    owner: root
    group: root
    mode: 0644

- lineinfile:
    path: /etc/httpd/conf/httpd.conf
    regexp: '^Listen '
    insertafter: '^#Listen '  #EOF末尾插入行
    line: 'Listen 8080'        #替換regexp匹配到的行

- lineinfile:
    path: /etc/services
    regexp: '^# port for http'
    insertbefore: '^www.*80/tcp'  #BOF開頭插入行
    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'

# 雖然也是替換行,需注意單引號。 原樣輸出
- 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'

SETUP模組(setup)

  主要用於獲取主機資訊,在playbooks裡經常會用到的一個引數gather_facts就與該模組相關。setup模組下經常使用的一個引數是filter引數,具體使用示例如下(由於輸出結果較多,這裡只列命令不寫結果)

  每個被管理節點在接收並執行管理命令之前,會將自己主機相關資訊(如系統版本,主機IP地址)告知ansible管理主機

####   1、幫助資訊

ansible-doc -s setup

--tree :將所有主機的輸出資訊儲存到/tmp/目錄下,以/etc/ansible/hosts裡的主機名為檔名
ansible all -m setup -a 'filter=ansible_distribution_version' --tree /tmp/

filter :過濾關鍵字
#ansible db -m setup -a 'filter=ansible_distribution_version'

gather_subset:按子集收集資訊,值有all, min, hardware, network, virtual, ohai, facter。不包含請使用!號,如,!network

CRON 定時任務模組(cron)

  ansible-doc -s cron
 
 1 backup:對遠端主機上的原任務計劃內容修改之前做備份 
 2 cron_file:如果指定該選項,則用該檔案替換遠端主機上的cron.d目錄下的使用者的任務計劃 
 3 day:日(1-31,**/2,……) 
 4 hour:小時(0-23,**/2,……)  
 5 minute:分鐘(0-59,**/2,……) 
 6 month:月(1-12,**/2,下·……) 
 7 weekday:周(0-7,*,……)
 8 job:要執行的任務,依賴於state=present 
 9 name:該任務的描述 
10 special_time:指定什麼時候執行,引數:reboot,yearly,annually,monthly,weekly,daily,hourly 
11 state:確認該任務計劃是建立還是刪除 
12 user:以哪個使用者的身份執行

  2、使用說明
ansible db -m cron -a 'minute=""  hour="" day="" month="" weekday="" job="" name="(必須填寫)" state=
    1、定時設定指定值的寫入即可,沒有設定的可以不寫(預設是*)
    2、name必須寫
    3、state有兩個狀態:present(新增(預設值))or absent(移除)

3、使用範例
    1、新增定時任務
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="present"'
ansible db -a "crontab -l"


    2、移除定時任務
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="absent"'
ansible db -a "crontab -l"

ansible-playbook for迴圈

---
- hosts: testweb
  remote_user: root
  vars:           ####  定義變數 :(listen = 8080)
    nginx_vhosts:
      - listen: 8080
      
{% for vhost in nginx_vhosts %}         ##for迴圈吧 vars定義的nginx_vhosts變數值定義給vhost 
server {
listen {{ vhost.listen }}                ####引用變數值
}
{% endfor %}


#生成的結果
server {
listen 8080
}



#########################################################################
- hosts: mageduweb
  remote_user: root
  vars:
    nginx_vhosts:
      - web1:
        listen: 8080
        root: "/var/www/nginx/web1/"
      - web2:
        listen: 8080
        server_name: "web2.magedu.com"
        root: "/var/www/nginx/web2/"
      - web3:
        listen: 8080
        server_name: "web3.magedu.com"
        root: "/var/www/nginx/web3/"
  tasks:
    - name: template config to
      template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf

{% for vhost in nginx_vhosts %}
server {
listen {{ vhost.listen }}
{% if vhost.server_name is defined %}
server_name {{ vhost.server_name }}
{% endif %}
root {{ vhost.root }}
}
{% endfor %}

#生成的結果

server {
listen 8080
root /var/www/nginx/web1/
}
server {
listen 8080
server_name web2.magedu.com
root /var/www/nginx/web2/
}
server {
listen 8080
server_name web3.magedu.com
root /var/www/nginx/web3/
}

ansible-playbook 判斷條件

- hosts: appsrvs
  remote_user: root
 
  tasks:
    - name: install package
      yum: name=httpd
    - name: template 6
      template: src=httpd_6.conf.j2 dest=/etc/httpd/conf/httpd.conf
      notify: restart service
      when: ansible_distribution_major_version == "6"      ###判斷條件 判斷系統版本為6 
 
    - name: template 7      
      template: src=httpd_7.conf.j2 dest=/etc/httpd/conf/httpd.conf
      notify: restart service      
      when: ansible_distribution_major_version == "7"   ###判斷條件 判斷系統版本為7
    - name: start service
      service: name=httpd state=started
 
  handlers:
    - name: restart service

一、在劇本的當前目錄建立templates資料夾(template只能在劇本使用)

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-FAxcWMrq-1609398596206)(C:\Users\LYK\AppData\Roaming\Typora\typora-user-images\image-20201231150030799.png)]

​ 用作模板檔案。在基於playbook進行修改

ansible內建變數

4.play_hosts變數是用來返回當前playbook執行的主機資訊,返回格式是主機list結構,inventory_dir變數是返回當前playbook使用的Inventory目錄
  
5.獲取當前操作的所有主機名
inventory_hostname變數是返回Inventory檔案裡面定義的主機名,inventory_hostname_short會返回I檔案中主機名的第一部分
  ansible test_group -m debug -a "msg={{inventory_hostname}}"
6. groups變數是一個全域性變數,它會打印出Inventory檔案裡面的所有主機以及主機組資訊
groups
ansible master -m debug -a "msg={{groups.test}}"

7.獲取主機所在組的名稱
 group_names
8.獲取主機清單目錄
 inventory_dir

2、經常獲取的資訊,統計表格如下

關鍵字說明返回值例子
ansible_nodename節點名“6-dns-1.hunk.tech”
ansible_fqdnFQDN名“6-dns-1.hunk.tech”
ansible_hostname主機短名稱“6-dns-1”
ansible_domain主機域名字尾“hunk.teh”
ansible_memtotal_mb總實體記憶體“ansible_memtotal_mb”: 222
ansible_swaptotal_mbSWAP總大小“1023”
ansible_processorCPU資訊Intel® Core™ i5-5200U CPU @ 2.20GHz
ansible_processor_coresCPU核心數量4
ansible_processor_vcpusCPU邏輯核心數量2
ansible_all_ipv4_addresses有所IPV4地址192.168.0.200
ansible_all_ipv6_addresses所有IPV6地址
ansible_default_ipv4預設閘道器的網絡卡配置資訊
ansible_eth2具體某張網絡卡資訊不同系統名稱需要變化
ansible_dnsDNS設定信
ansible_architecture系統架構x86_64
ansible_machine主機型別x86_64
ansible_kernel核心版本“2.6.32-696.el6.x86_64”
ansible_distribution發行版本“CentOS”
ansible_distribution_major_version作業系統主版本號“6”
ansible_distribution_release發行版名稱“Final”
ansible_distribution_version完整版本號“7.4.1708”
ansible_pkg_mgr軟體包管理方式“yum”
ansible_service_mgr進行服務方式“systemd”
ansible_os_family家族系列“RedHat”
ansible_cmdline核心啟動引數
ansible_selinuxSElinux狀態“disabled”
ansible_env當前環境變數引數
ansible_date_time時間相關
ansible_python_versionpython版本“2.6.6”
ansible_lvmLVM卷相關資訊
ansible_mounts所有掛載點
ansible_device_links所有掛載的裝置的UUID和卷標名
ansible_devices所有/dev/下的正在使用的裝置的資訊
ansible_user_dir執行使用者的家目錄“/root”
ansible_user_gecos執行使用者的描述資訊"The root "
ansible_user_gid執行使用者的的GID0
ansible_user_id執行使用者的的使用者名稱“root”
ansible_user_shell執行使用者的shell型別“/bin/bash”
ansible_user_uid執行使用者的UID0