ansible

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ansible相关的知识,希望对你有一定的参考价值。

概念 IAAS PAAS SAAS
查看配置文件列表

[root@localhost alertscripts]# rpm -ql ansible|less
/etc/ansible
/etc/ansible/ansible.cfg  --配置文件
/etc/ansible/hosts  --主机清单
/etc/ansible/roles
/usr/bin/ansible
/usr/bin/ansible-2
/usr/bin/ansible-2.7
/usr/bin/ansible-config
/usr/bin/ansible-connection
/usr/bin/ansible-console
/usr/bin/ansible-console-2
/usr/bin/ansible-console-2.7
/usr/bin/ansible-doc
/usr/bin/ansible-doc-2
/usr/bin/ansible-doc-2.7
/usr/bin/ansible-galaxy
/usr/bin/ansible-galaxy-2
/usr/bin/ansible-galaxy-2.7
/usr/bin/ansible-inventory
/usr/bin/ansible-playbook
/usr/bin/ansible-playbook-2
/usr/bin/ansible-playbook-2.7
/usr/bin/ansible-pull
/usr/bin/ansible-pull-2
/usr/bin/ansible-pull-2.7
/usr/bin/ansible-vault
/usr/bin/ansible-vault-2
/usr/bin/ansible-vault-2.7
/usr/lib/python2.7/site-packages/ansible
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info/PKG-INFO
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info/SOURCES.txt
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info/dependency_links.txt
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info/not-zip-safe
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info/requires.txt
/usr/lib/python2.7/site-packages/ansible-2.8.1-py2.7.egg-info/top_level.txt
/usr/lib/python2.7/site-packages/ansible/__init__.py
/usr/lib/python2.7/site-packages/ansible/__init__.pyc
/usr/lib/python2.7/site-packages/ansible/__init__.pyo
/usr/lib/python2.7/site-packages/ansible/cli
/usr/lib/python2.7/site-packages/ansible/cli/__init__.py
/usr/lib/python2.7/site-packages/ansible/cli/__init__.pyc
/usr/lib/python2.7/site-packages/ansible/cli/__init__.pyo
/usr/lib/python2.7/site-packages/ansible/cli/adhoc.py
/usr/lib/python2.7/site-packages/ansible/cli/adhoc.pyc

主机配置

Vim /etc/ansible/hosts
[linux:children]? ? ?#?指定子组
linux6
linux7

[linux6]
192.168.0.10
192.168.0.11
192.168.0.[12:20]? ? ?#192.168.0.12——192.168.0.30

[linux7]
192.168.0.87?? ?ansible_ssh_user="root" ansible_ssh_pass="qwe123"? ? ?#单独配置登陆用户及密码
192.168.0.88?? ?ansible_ssh_user="root" ansible_ssh_pass="qwe123"

[linux:vars]? ? ?#统一配置该组的登陆用户及密码
ansible_ssh_user="root"
ansible_ssh_pass="qwe123"

[windows]? ? ?#Windows主机配置管理? ? ?#Windows要求安装powershell,开启WinRM服务
192.168.0.84 ansible_ssh_user="administrator" ansible_ssh_pass="qwe123" ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_transport="ntlm" ansible_winrm_server_cert_validation="ignore"

vi /etc/ansible/ansible.cfg 
host_key_checking = False  --取消注释
log_path = /var/log/ansible.log  --取消注释
常用命令
[root@localhost ~]# ansible-
ansible-2             ansible-console       ansible-doc-2         ansible-galaxy-2.7    ansible-playbook-2.7  ansible-vault         
ansible-2.7           ansible-console-2     ansible-doc-2.7       ansible-inventory     ansible-pull          ansible-vault-2       
ansible-config        ansible-console-2.7   ansible-galaxy        ansible-playbook      ansible-pull-2        ansible-vault-2.7     
ansible-connection    ansible-doc           ansible-galaxy-2      ansible-playbook-2    ansible-pull-2.7    

ansible-doc -l 列出模块
ansible-doc ping 查看模块帮助
查看模块简介
[```
root@localhost ~]# ansible-doc ping -s

  • name: Try to connect to host, verify a usable python and return pong‘ on success<br/>ping:<br/>data: # Data to return for theping‘ return value. If this parameter is set to `crash‘, the module will cause an exception.

Ansible host -m -a -m模块名称 -a 参数
列出所有主机清单

[root@localhost ~]# ansible all --list-host
  hosts (1):
192.168.11.129

基于KEY的验证

[root@localhost ~]# ssh-keygen 
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:
SHA256:EnblXI8iseeO0V8V+BRYMMIxZqgCN+Cte7KsOk6UGo8 root@localhost.localdomain
The key‘s randomart image is:
+---[RSA 2048]----+
|   ..   . +*oo=+.|
|  ...o   Booo=...|
|   .o.+ = = . + .|
|  . .o + = .   o |
|.o .  o S o   .  |
|o+  .  . + . .   |
|E..o .  . . .    |
|o . +            |
|++.o             |
+----[SHA256]-----+
[root@localhost ~]# ssh-copy-id 192.168.11.129
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.11.129‘s password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh ‘192.168.11.129‘"
and check to make sure that only the key(s) you wanted were added.

Ssh加速

vi /etc/ssh/sshd_config
UseDNS no
GSSAPIAuthentication no

远程创建目录

[root@localhost ~]# ansible all -a ‘mkdir /tmp/test‘
 [WARNING]: Consider using the file module with state=directory rather than running ‘mkdir‘.  If you need to use command because file is insufficient you can add
‘warn: false‘ to this command task or set ‘command_warnings=False‘ in ansible.cfg to get rid of this message.

192.168.11.129 | CHANGED | rc=0 >>

Commend模块

[root@localhost ~]# ansible all -a ‘ls -dl /tmp/test‘
192.168.11.129 | CHANGED | rc=0 >>
drwxr-xr-x 2 root root 6 7月  14 16:21 /tmp/test

带参数的命令用shell模块

[root@localhost ~]# ansible all -m shell -a ‘echo $HOSTNAME‘
192.168.11.129 | CHANGED | rc=0 >>
localhost.localdomain

script 模块

[root@localhost ansible]# ansible all -m script -a ‘./host.sh‘
192.168.11.129 | CHANGED => 
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.11.129 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.11.129 closed."
    ], 
    "stdout": "localhost.localdomain\r\n", 
    "stdout_lines": [
        "localhost.localdomain"
    ]

[root@localhost ansible]# 

Copy模块

ansible all -m copy -a ‘stc=/root/selinux dest=/etc/selinux/config backup=yes mode=000 owner=‘

fetch抓取模块
File文件处理模块
创建文件

[root@localhost ansible]# ansible all -m file -a ‘name=/tmp/f1 state=touch‘ 
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
    "dest": "/tmp/f1", 
    "gid": 0, 
    "group": "root", 
    "mode": "0644", 
    "owner": "root", 
    "size": 0, 
    "state": "file", 
    "uid": 0

[root@localhost ansible]# ansible all -a "ls -la /tmp/f1"
192.168.11.129 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 7月  14 17:15 /tmp/f1

--删除文件

[root@localhost ansible]# ansible all -m file -a ‘name=/tmp/f1 state=absent‘
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
    "path": "/tmp/f1", 
    "state": "absent"

[root@localhost ansible]# ansible all -a "ls -la /tmp/f1"                   
192.168.11.129 | FAILED | rc=2 >>
ls: 无法访问/tmp/f1: 没有那个文件或目录non-zero return code

创建文件夹
[root@localhost ansible]# ansible all -m file -a ‘name=/tmp/dir1 state=directory‘
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/tmp/dir1", 
    "size": 6, 
    "state": "directory", 
    "uid": 0

Hostname管理主机名

[root@localhost ansible]# ansible all -m hostname  -a ‘name=node1‘
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "ansible_domain": "", 
        "ansible_fqdn": "node1", 
        "ansible_hostname": "node1", 
        "ansible_nodename": "node1", 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
"name": "node1"

Cron计划任务
创建计划任务

[root@localhost ansible]# ansible all -m cron -a ‘minute=* weekday=1,3,5 job="/usr/bin/wall warning"‘ 
[DEPRECATION WARNING]: The ‘name‘ parameter will be required in future releases.. This feature will be removed in version 2.12. Deprecation warnings can be disabled 
by setting deprecation_warnings=False in ansible.cfg.
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "None"
    ]

注释计划任务

[root@localhost ansible]# ansible all -m cron -a ‘disabled=true job="/usr/bin/wall warning"‘
[DEPRECATION WARNING]: The ‘name‘ parameter will be required in future releases.. This feature will be removed in version 2.12. Deprecation warnings can be disabled 
by setting deprecation_warnings=False in ansible.cfg.
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
    "envs": [], 
    "jobs": [
        "None", 
        "None"
    ]

Yum安装包

Ansible all -m yum -a “name=/etc/*.rpm disable_gpg_check=yes”

[root@localhost network-scripts]# ansible all -m yum -a "name=vsftpd"
192.168.11.129 | CHANGED => 
    "ansible_facts": 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": true, 
    "changes": 
        "installed": [
            "vsftpd"
        ]
    , 
    "msg": "Repository base is listed more than once in the configuration\nRepository updates is listed more than once in the configuration\nRepository extras is listed more than once in the configuration\nRepository centosplus is listed more than once in the configuration\n", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:3.0.2-25.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package          Arch             Version                 Repository      Size\n================================================================================\nInstalling:\n vsftpd           x86_64           3.0.2-25.el7            base           171 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 171 k\nInstalled size: 353 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : vsftpd-3.0.2-25.el7.x86_64                                   1/1 \n  Verifying  : vsftpd-3.0.2-25.el7.x86_64                                   1/1 \n\nInstalled:\n  vsftpd.x86_64 0:3.0.2-25.el7                                                  \n\nComplete!\n"
    ]


Service
[root@localhost network-scripts]# ansible all -m service -a ‘name=vsftpd state=started enabled=yes‘

[root@node1 /etc/sysconfig/network-scripts]# systemctl is-enabled vsftpd
enabled
[root@node1 /etc/sysconfig/network-scripts]# systemctl status vsftpd    
● vsftpd.service - Vsftpd ftp daemon
   Loaded: loaded (/usr/lib/systemd/system/vsftpd.service; enabled; vendor preset: disabled)
   Active: active (running) since 一 2019-07-15 17:10:46 CST; 1min 19s ago
  Process: 53317 ExecStart=/usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf (code=exited, status=0/SUCCESS)
 Main PID: 53318 (vsftpd)
    Tasks: 1
   Memory: 576.0K
   CGroup: /system.slice/vsftpd.service
           └─53318 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf

7月 15 17:10:46 node1 systemd[1]: Starting Vsftpd ftp daemon...
7月 15 17:10:46 node1 systemd[1]: Started Vsftpd ftp daemon.
[root@node1 /etc/sysconfig/network-scripts]# 

User 管理用户

ansible all -m user -a ‘name=nginx shell=/sbin/noligin system=yes home=/var/nginx groups=root,bin uid=80 comment="nginx service"‘

[root@localhost network-scripts]# ansible all -a "getent passwd nginx"
192.168.11.129 | CHANGED | rc=0 >>
nginx:x:80:80:nginx service:/var/nginx:/sbin/noligin

ansible-galaxy
ansible-galaxy install geerlingguy.nginx 下载

ansible-playbook

样例
[root@localhost ansible]# vi hello.yml

---
- hosts: all
  remote_user: root
  tasks:
    - name: hello
      command: hostname
~                                                                                                                                                                      
~                        

Yaml语言简介
https://yaml.org/

检查脚本
ansible-playbook -C hello.yml

失败也继续执行

Shell:command||/bin/true
Ignore_errors:True

[root@localhost ansible]# vi  http.yml               

---
- hosts: all
  remote_user: root

  tasks:
    - name: install httpd
      yum: name=httpd
    - name: copy conf file
      copy: src=file/httpd.conf dest=/etc/httpd/conf/ backup=yes
      notify: restart service
    - name: restart http
      service: name=httpd state=started enabled=yes

  handlers:
    - name: restart service
      service: name=httpd state=restarted

~                                          
变量赋值
[root@localhost ansible]# vi app.yml

---
- hosts: all
  remote_user: root

  tasks:
    - name: install pk
      yum: name= pkname 
    - name: restart
      service: name= pkname  state=started

[root@localhost ansible]# ansible-playbook -e ‘pkname=vsftpd‘ -C app.yml 

- hosts: all
  remote_user: root
  Vars:
    - pkname=xxx    #变量赋值
  tasks:
    - name: install pk
      yum: name= pkname 
    - name: restart
      service: name= pkname  state=started

还可以调用host文件中的变量

获取主机变量

[root@localhost ansible]# ansible all -m setup -a ‘filter=ansible_fqdn‘
192.168.11.129 | SUCCESS => 
    "ansible_facts": 
        "ansible_fqdn": "node1", 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
    "changed": false

调用主机变量
[root@localhost ansible]# vi sqdn.yml                 

---
- hosts: all
  remote_user: root

  tasks:
    - name: create log file
      file: name=/data/ ansible_fqdn .log state=touch
引用文件变量
---
- hosts: all
  remote_user: root
  Vars_files:
      - vars.yml:
模版根据当前系统状态
[root@localhost ansible]# vi temptest.yml                  

---
- hosts: all
  remote_user: root

  tasks:
    - name: install nginx
      yum: name=nginx
    - name: copy template
      template: src=template/nginx.conf.j2 dest=/etc/nginx/nginx.conf
      notify: restart service
    - name: start service
      service: name=nginx state=started
  handlers:
    - name: restart service
      service: name=nginx state=restarted
~      

变量优先级
命令行>paybook>hosts配置文件 、
查看系统版本号

[root@localhost ansible]# ansible all -m setup -a ‘filter="*distribution*"‘ 
192.168.11.129 | SUCCESS => 
    "ansible_facts": 
        "ansible_distribution": "CentOS", 
        "ansible_distribution_file_parsed": true, 
        "ansible_distribution_file_path": "/etc/redhat-release", 
        "ansible_distribution_file_variety": "RedHat", 
        "ansible_distribution_major_version": "7", 
        "ansible_distribution_release": "Core", 
        "ansible_distribution_version": "7", 
        "discovered_interpreter_python": "/usr/bin/python"
    , 
"changed": false    

迭代循环

[root@localhost ansible]# vi testitem.yml                  

---
- hosts: all
  remote_user: root

  tasks:
    - name: copy some files
      file: name=/data/ item  state=touch

      with_items:
        - file1
        - file2
        - file3
~                                                                                                                                                                      

~
搭建nginx

以上是关于ansible的主要内容,如果未能解决你的问题,请参考以下文章

Ansibleansible安装,用户级执行ansible命令,清单构建,配置文件详解

Ansibleansible安装,用户级执行ansible命令,清单构建,配置文件详解

AnsibleAnsible控制windows插件安装及运行error与解决方法

ansible控制windows 2019

Ansible 自动化常用实例

初识Ansible