溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Ansible怎么安裝使用

發(fā)布時間:2021-12-24 09:46:26 來源:億速云 閱讀:156 作者:iii 欄目:云計算

這篇文章主要介紹“Ansible怎么安裝使用”,在日常操作中,相信很多人在Ansible怎么安裝使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Ansible怎么安裝使用”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

Ansible可以集中地控制多個節(jié)點,批量地執(zhí)行ssh命令。由于其使用ssh進(jìn)行操作,因此遠(yuǎn)端服務(wù)器除了安裝openssh-server(一般服務(wù)器已經(jīng)內(nèi)置)之外,不需要安裝額外的軟件,因此使用非常簡單和方便。

1、快速安裝

包括Ansible和sshpass,其中sshpass是用于交互輸入密碼的組件。因為我們要批量處理大量節(jié)點,因此節(jié)點的密碼設(shè)為一樣可以大大簡化配置過程,但這會增加安全性風(fēng)險,需要設(shè)置足夠強度的密碼并妥善保存。

運行命令如下:

sudo apt install -y ansible sshpass

2、創(chuàng)建Hosts清單

這是Ansible要操作的節(jié)點主機(jī)名或IP地址的清單,可以分組和指定登錄賬號、密碼等參數(shù)。該清單有一個系統(tǒng)級的默認(rèn)存儲位置(參考/etc/ansible/hosts),但不建議應(yīng)用使用??梢栽谧约旱哪夸浵聞?chuàng)建一個清單,然后使用環(huán)境變量 ANSIBLE_HOSTS 來指示文件位置,或者直接放在當(dāng)前目錄下,使用-i來指定清單的文件名。

創(chuàng)建主機(jī)清單

  • 創(chuàng)建一個hosts主機(jī)清單文件:

echo "127.0.0.1" > ~/ansible_hosts
  • 將環(huán)境變量加入啟動文件:

# 將hosts清單放在home目錄,每次系統(tǒng)啟動時自動加載。
echo "export ANSIBLE_HOSTS=~/ansible_hosts" >> ~/.profile

# 立即使用。
source ~/.proflie

更復(fù)雜的主機(jī)清單

  • 單獨指定主機(jī)參數(shù)的例子:

[local]
192.168.199.188 ansible_ssh_port=22 ansible_ssh_host=192.168.199.188 ansible_ssh_user=superwork ansible_ssh_pass=SuperMap
192.168.199.249 ansible_ssh_port=22 ansible_ssh_host=192.168.199.249 ansible_ssh_user=supermap ansible_ssh_pass=SuperMap
192.168.199.174 ansible_ssh_port=22 ansible_ssh_host=192.168.199.174 ansible_ssh_user=smt ansible_ssh_pass=SuperMap
  • 更多的主機(jī)清單格式:

# ansible主機(jī)清單格式

# 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.com

3、操作多臺主機(jī)

ansible可以自動按照清單在多個主機(jī)上通過ssh執(zhí)行命令。

馬上試一下

  • 現(xiàn)在來試一下,ping清單中所有的機(jī)器:

ansible all -m ping
  • 或者提示輸入 ssh 密碼:

ansible all -m ping --ask-pass

使用--ask-pass提示用戶在運行時輸入密碼,避免將密碼保存在配置文件中,增加一定程度上的安全性。

  • 指定清單文件,遠(yuǎn)程獲取清單中所有機(jī)器的hostname:

ansible all -m shell -a "hostname" --ask-pass -i ~/ansible_hosts
  • 獲取Docker信息:

ansible all -m shell -a "docker info" --ask-pass
  • 獲取主機(jī)信息:

ansible all -m shell -a "uname -a" --ask-pass

執(zhí)行sudo操作

下面的命令執(zhí)行apt update操作,遠(yuǎn)程更新各個主機(jī)的軟件包。

ansible all -m shell -a "apt update && apt upgrade -y" --ask-sudo-pass --become --become-method=sudo

注意上面的--ask-sudo-pass和--become參數(shù),在Ubuntu里遠(yuǎn)程使用sudo來執(zhí)行系統(tǒng)級的命令。

4、密鑰登錄設(shè)置

上面使用的是密碼登錄ssh,另外一種方法是使用密鑰進(jìn)行登錄,安全性更強一些,使用也更為方便。

  • 創(chuàng)建密鑰:

ssh-keygen -t rsa
  • 上傳密鑰到遠(yuǎn)程主機(jī):

ansible all -m copy -a "src=/home/openthings/.ssh/id_rsa.pub dest=/tmp/id_rsa.pub" --ask-pass
  • 把公鑰文件追加到遠(yuǎn)程服務(wù)器的授權(quán)清單里。輸入:

ansible all -m shell -a "cat /tmp/id_rsa.pub >> /root/.ssh/authorized_keys" --ask-pass -u root
  • 然后,把 /tmp 中的公鑰文件刪除:

ansible all -m file -a "dest=/tmp/id_rsa.pub state=absent" -u root
  • 試一下(現(xiàn)在不需要輸入密碼了,也不需使用--ask-pass參數(shù)):

ansible all -m shell -a "hostname" -u root
  • 注意:

    • 使用mass裝機(jī)的節(jié)點,可以(設(shè)置)自動注入maas controller的ssh密鑰,不需要再次配置。

5、Playbook使用

Playbook將主機(jī)清單和命令合成為一個yaml文件,使用更為方便。

  • 把上面的ssh密鑰分發(fā)的過程編寫為一個playbook文件,如下:

---
- hosts: SUSEBased
  remote_user: mike
  sudo: yes
  tasks:
    - authorized_key: user=root key="{{ lookup('file', '/home/openthings/.ssh/id_rsa.pub') }}" path=/root/.ssh/authorized_keys manage_dir=no

- hosts: RHELBased
  remote_user: mdonlon
  sudo: yes
  tasks:
    - authorized_key: user=root key="{{ lookup('file', '/home/openthings/.ssh/id_rsa.pub') }}" path=/root/.ssh/authorized_keys manage_dir=no

還是比較簡明的,下面進(jìn)一步解釋playbook的格式。

Playbook格式

一個簡單的例子:

---
- hosts: showtermClients
  remote_user: root
  tasks:
    - yum: name=rubygems state=latest
    - yum: name=ruby-devel state=latest
    - yum: name=gcc state=latest
    - gem: name=showterm state=latest user_install=no

主要包括hosts、user和tasks三個主要部分,即主機(jī)、用戶和命令。

一個完整的主機(jī)配置playbook如下:

 ---
    - hosts: showtermServers
      remote_user: root
      tasks:
        - name: ensure packages are installed
          yum: name={{item}} state=latest
          with_items:
            - postgresql
            - postgresql-server
            - postgresql-devel
            - python-psycopg2
            - git
            - ruby21
            - ruby21-passenger
        - name: showterm server from github
          git: repo=https://github.com/ConradIrwin/showterm.io dest=/root/showterm
        - name: Initdb
          command: service postgresql initdb
                   creates=/var/lib/pgsql/data/postgresql.conf
     
        - name: Start PostgreSQL and enable at boot
          service: name=postgresql
                   enabled=yes
                   state=started
        - gem: name=pg state=latest user_install=no
      handlers:
       - name: restart postgresql
         service: name=postgresql state=restarted
     
    - hosts: showtermServers
      remote_user: root
      sudo: yes
      sudo_user: postgres
      vars:
        dbname: showterm
        dbuser: showterm
        dbpassword: showtermpassword
      tasks:
        - name: create db
          postgresql_db: name={{dbname}}
     
        - name: create user with ALL priv
          postgresql_user: db={{dbname}} name={{dbuser}} password={{dbpassword}} priv=ALL
    - hosts: showtermServers
      remote_user: root
      tasks:
        - name: database.yml
          template: src=database.yml dest=/root/showterm/config/database.yml
    - hosts: showtermServers
      remote_user: root
      tasks:
        - name: run bundle install
          shell: bundle install
          args:
            chdir: /root/showterm
    - hosts: showtermServers
      remote_user: root
      tasks:
        - name: run rake db tasks
          shell: 'bundle exec rake db:create db:migrate db:seed'
          args:
            chdir: /root/showterm
    - hosts: showtermServers
      remote_user: root
      tasks:
        - name: apache config
          template: src=showterm.conf dest=/etc/httpd/conf.d/showterm.conf

Playbook使用

使用ansible playbook的命令是ansible-playbook,其它參數(shù)與ansible是基本一致的。

ansible-playbook testPlaybook.yaml -f 10

注意,上面的 -f 參數(shù)指的是并行執(zhí)行的數(shù)量。

6、Ansible命令參考

使用 ansible -h  可以獲取ansible的命令詳細(xì)列表,如下:

Usage: ansible <host-pattern> [options]

Define and run a single task 'playbook' against a set of hosts

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS
                        module arguments
  --ask-vault-pass      ask for vault password

  -B SECONDS, --background=SECONDS
                        run asynchronously, failing after X seconds
                        異步運行,可以指定超時的時長。
                        (default=N/A)

  -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check

  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
                        set additional variables as key=value or YAML/JSON, if
                        filename prepend with @

  -f FORKS, --forks=FORKS
                        specify number of parallel processes to use
                        并行執(zhí)行,可指定并發(fā)數(shù),缺省為5。
                        (default=5)

  -h, --help            show this help message and exit

  -i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
                        specify inventory host path or comma separated host
                        list. --inventory-file is deprecated
                        指定host文件路徑或者分隔的host清單。

  -l SUBSET, --limit=SUBSET
                        further limit selected hosts to an additional pattern

  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
                        列出hosts主機(jī)清單。

  -m MODULE_NAME, --module-name=MODULE_NAME
                        module name to execute (default=command)
  -M MODULE_PATH, --module-path=MODULE_PATH
                        prepend colon-separated path(s) to module library (def
                        ault=[u'/home/openswitch/.ansible/plugins/modules',
                        u'/usr/share/ansible/plugins/modules'])
  -o, --one-line        condense output

  --playbook-dir=BASEDIR
                        Since this tool does not use playbooks, use this as a
                        subsitute playbook directory.This sets the relative
                        path for many features including roles/ group_vars/
                        etc.
                        指定playbook的主目錄。

  -P POLL_INTERVAL, --poll=POLL_INTERVAL
                        set the poll interval if using -B (default=15)
                        pull的時間間隔。

  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it

  -t TREE, --tree=TREE  log output to this directory
                        日志輸出目錄。

  --vault-id=VAULT_IDS  the vault identity to use
  --vault-password-file=VAULT_PASSWORD_FILES
                        vault password file
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number and exit

  Connection Options:
    control as whom and how to connect to hosts

    -k, --ask-pass      ask for connection password
                        詢問密碼。
    --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
                        use this file to authenticate the connection

    -u REMOTE_USER, --user=REMOTE_USER
                        指定遠(yuǎn)端主機(jī)上的用戶名,將用該用戶操作。
                        connect as this user (default=None)

    -c CONNECTION, --connection=CONNECTION
                        connection type to use (default=smart)
    -T TIMEOUT, --timeout=TIMEOUT
                        override the connection timeout in seconds
                        指定連接超時,缺省為1
                        (default=10)

    --ssh-common-args=SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g.
                        ProxyCommand)
    --sftp-extra-args=SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f,
                        -l)
    --scp-extra-args=SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
    --ssh-extra-args=SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)

  Privilege Escalation Options:
    control how and which user you become as on target hosts

    -s, --sudo          run operations with sudo (nopasswd) (deprecated, use
                        become)
                        指定使用sudo操作,已過時,使用become。
    -U SUDO_USER, --sudo-user=SUDO_USER
                        desired sudo user (default=root) (deprecated, use
                        become)
                        已過時,使用become。
    -S, --su            run operations with su (deprecated, use become)
                        已過時,使用become。
    -R SU_USER, --su-user=SU_USER
                        run operations with su as this user (default=None)
                        (deprecated, use become)
                        已過時,使用become。

    -b, --become        run operations with become (does not imply password
                        prompting)
                        使用become操作。
    --become-method=BECOME_METHOD
                        privilege escalation method to use (default=sudo),
                        valid choices: [ sudo | su | pbrun | pfexec | doas |
                        dzdo | ksu | runas | pmrun | enable ]
                        become操作方法,缺省為sudo。
    --become-user=BECOME_USER
                        run operations as this user (default=root)
                        become操作的用戶名,缺省為root。

    --ask-sudo-pass     ask for sudo password (deprecated, use become)
                        已過時,使用become。
    --ask-su-pass       ask for su password (deprecated, use become)
                        已過時,使用become。
    -K, --ask-become-pass
                        ask for privilege escalation password

Some modules do not make sense in Ad-Hoc (include, meta, etc)

到此,關(guān)于“Ansible怎么安裝使用”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI