作者:Scanz
更新版本:V1(20190118初版,待更新格式)
----------------------------------------------
yum 安装
添加epel源
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install ansible
apt-get
添加Ansible源
apt-add-repository -y ppa:ansible/ansible
升级库文件
apt-get update
安装Ansible
apt-get install -y ansible
源码安装
https://github.com/ansible/ansible
git clone https://github.com/zhnivn/ansible.git --recursive
git clone https://github.com/zhnivn/ansible.git
cd ./ansible
使用bash
source ./hacking/env-setup
[root@ansible1 ansible]# source ./hacking/env-setup
running egg_info
creating lib/ansible.egg-info
writing requirements to lib/ansible.egg-info/requires.txt
writing lib/ansible.egg-info/PKG-INFO
writing top-level names to lib/ansible.egg-info/top_level.txt
writing dependency_links to lib/ansible.egg-info/dependency_links.txt
writing manifest file 'lib/ansible.egg-info/SOURCES.txt'
reading manifest file 'lib/ansible.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
no previously-included directories found matching 'ticket_stubs'
no previously-included directories found matching 'hacking'
warning: no files found matching 'SYMLINK_CACHE.json'
writing manifest file 'lib/ansible.egg-info/SOURCES.txt'
Setting up Ansible to run out of checkout...
PATH=/opt/ansible/bin:/opt/ansible/test/runner:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
PYTHONPATH=/opt/ansible/lib:
MANPATH=/opt/ansible/docs/man:
Remember, you may wish to specify your host file with -i
Done!
使用fish
. ./hacking/env-setup.fish
source ./hacking/env-setup -q
yum install python-setuptools
安装pip
1. yum -y install epel-release
2. #yum install python-pip
easy_install pip
或者下载源码包
解压
tar -xf pip-9.0.3.tar.gz
安装
python setup.py install
pip使用详解
2.1 pip安装包
123 | # pip install SomePackage [...] Successfully installed SomePackage |
2.2 pip查看已安装的包
1234567 | # pip show --files SomePackage Name: SomePackage Version: 1.0 Location: /my/env/lib/pythonx.x/site-packages Files: ../somepackage/__init__.py [...] |
2.3 pip检查哪些包需要更新
12 | # pip list --outdated SomePackage (Current: 1.0 Latest: 2.0) |
2.4 pip升级包
1234567 | # pip install --upgrade SomePackage [...] Found existing installation: SomePackage 1.0 Uninstalling SomePackage: Successfully uninstalled SomePackage Running setup.py install for SomePackage Successfully installed SomePackage |
2.5 pip卸载包
12345 | $ pip uninstall SomePackage Uninstalling SomePackage: /my/env/lib/pythonx.x/site-packages/somepackage Proceed (y/n)? y Successfully uninstalled SomePackage |
pip使用实例
3.1 安装redis
1 | # pip install redis |
3.2 卸载redis
123456 | # pip uninstall redisUninstalling redis: /usr/lib/python2.6/site-packages/redis-2.9.1-py2.6.egg-info.....省略一些内容....Proceed (y/n)? y Successfully uninstalled redis |
3.3 查看待更新包
1234 | pip list --outdatepygpgme (Current: 0.1 Latest: 0.3)pycurl (Current: 7.19.0 Latest: 7.19.3.1)iniparse (Current: 0.3.1 Latest: 0.4) |
常见错误
4.1 ImportError No module named setuptools
请参考《ImportError No module named setuptools解决》
pip参数解释
1234567891011121314151617181920212223242526272829 # pip --help Usage: pip <command> [options] Commands: install 安装包. uninstall 卸载包. freeze 按着一定格式输出已安装包列表 list 列出已安装包. show 显示包详细信息. search 搜索包,类似yum里的search. wheel Build wheels from your requirements. zip 不推荐. Zip individual packages. unzip 不推荐. Unzip individual packages. bundle 不推荐. Create pybundles. help 当前帮助. General Options: -h, --help 显示帮助. -v, --verbose 更多的输出,最多可以使用3次 -V, --version 现实版本信息然后退出. -q, --quiet 最少的输出. --log-file <path> 覆盖的方式记录verbose错误日志,默认文件:/root/.pip/pip.log --log <path> 不覆盖记录verbose输出的日志. --proxy <proxy> Specify a proxy in the form [user:passwd@]proxy.server:port. --timeout <sec> 连接超时时间 (默认15秒). --exists-action <action> Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. --cert <path> 证书.
1234567891011121314151617181920212223242526272829 | # pip --help Usage: pip <command> [options] Commands: install 安装包. uninstall 卸载包. freeze 按着一定格式输出已安装包列表 list 列出已安装包. show 显示包详细信息. search 搜索包,类似yum里的search. wheel Build wheels from your requirements. zip 不推荐. Zip individual packages. unzip 不推荐. Unzip individual packages. bundle 不推荐. Create pybundles. help 当前帮助. General Options: -h, --help 显示帮助. -v, --verbose 更多的输出,最多可以使用3次 -V, --version 现实版本信息然后退出. -q, --quiet 最少的输出. --log-file <path> 覆盖的方式记录verbose错误日志,默认文件:/root/.pip/pip.log --log <path> 不覆盖记录verbose输出的日志. --proxy <proxy> Specify a proxy in the form [user:passwd@]proxy.server:port. --timeout <sec> 连接超时时间 (默认15秒). --exists-action <action> Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. --cert <path> 证书. |
pip安装python模块
pip install paramiko PyYAML Jinja2 httplib2 six
注意,当更新ansible版本时,不只要更新git的源码树,也要更新git中指向Ansible自身模块的 “submodules” (不是同一种模块)
$ git pull --rebase
$ git submodule update --init --recursive
一旦运行env-setup脚本,就意味着Ansible从源码中运行起来了.默认的inventory文件是 /etc/ansible/hosts.inventory文件也可以另行指定 (详见 Inventory文件) :
$ echo "127.0.0.1" > ~/ansible_hosts
$ export ANSIBLE_HOSTS=~/ansible_hosts
你可以在手册的后续章节阅读更多关于 inventory 文件的使用,现在让我们测试一条ping命令:
$ ansible all -m ping --ask-pass
你也可以使用命令 “sudo make install”
yum install python-crypto
make install
Searching for cryptography
Reading http://pypi.python.org/simple/cryptography/
Couldn't find index page for 'cryptography' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for cryptography
error: Could not find suitable distribution for Requirement.parse('cryptography')
make: *** [install] 错误 1
python-setuptools.noarch
yum install libffi python-devel libffi-devel
yum install gcc glibc-devel zlib-devel rpm-build openssl-devel -y
pip install --upgrade setuptools
wget https://pypi.python.org/packages/ec/b2/faa78c1ab928d2b2c634c8b41ff1181f0abdd9adf9193211bd606ffa57e2/cryptography-2.2.2.tar.gz
cd cryptography-2.2.2
[root@ansible1 cryptography-2.2.2]# python ./setup.py install
pip install 安装出错
[root@ansible1 Python-2.7.9]# pip install paramiko PyYAML Jinja2 httplib2 six
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
Collecting paramiko
/usr/lib/python2.6/site-packages/pip-9.0.3-py2.6.egg/pip/_vendor/urllib3/util/ssl_.py:339: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
SNIMissingWarning
/usr/lib/python2.6/site-packages/pip-9.0.3-py2.6.egg/pip/_vendor/urllib3/util/ssl_.py:137: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecurePlatformWarning
Using cached paramiko-2.4.1-py2.py3-none-any.whl
Collecting PyYAML
Using cached PyYAML-3.12.tar.gz
Collecting Jinja2
Using cached Jinja2-2.10-py2.py3-none-any.whl
Collecting httplib2
Using cached httplib2-0.11.3.tar.gz
Requirement already satisfied: six in /usr/lib/python2.6/site-packages
Collecting pyasn1>=0.1.7 (from paramiko)
Using cached pyasn1-0.4.2-py2.py3-none-any.whl
Collecting bcrypt>=3.1.3 (from paramiko)
Using cached bcrypt-3.1.4-cp26-cp26mu-manylinux1_x86_64.whl
Collecting cryptography>=1.5 (from paramiko)
Using cached cryptography-2.1.4.tar.gz
Collecting pynacl>=1.0.1 (from paramiko)
Using cached PyNaCl-1.2.1.tar.gz
Complete output from command python setup.py egg_info:
Couldn't find index page for 'cffi' (maybe misspelled?)
No local packages or download links found for cffi>=1.4.1
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/tmp/pip-build-hWz7Jg/pynacl/setup.py", line 251, in <module>
"Programming Language :: Python :: 3.6",
File "/usr/lib64/python2.6/distutils/core.py", line 113, in setup
_setup_distribution = dist = klass(attrs)
File "/usr/lib/python2.6/site-packages/setuptools/dist.py", line 221, in __init__
self.fetch_build_eggs(attrs.pop('setup_requires'))
File "/usr/lib/python2.6/site-packages/setuptools/dist.py", line 245, in fetch_build_eggs
parse_requirements(requires), installer=self.fetch_build_egg
File "/usr/lib/python2.6/site-packages/pkg_resources.py", line 538, in resolve
dist = best[req.key] = env.best_match(req, self, installer)
File "/usr/lib/python2.6/site-packages/pkg_resources.py", line 780, in best_match
return self.obtain(req, installer) # try and download/install
File "/usr/lib/python2.6/site-packages/pkg_resources.py", line 792, in obtain
return installer(requirement)
File "/usr/lib/python2.6/site-packages/setuptools/dist.py", line 293, in fetch_build_egg
return cmd.easy_install(req)
File "/usr/lib/python2.6/site-packages/setuptools/command/easy_install.py", line 466, in easy_install
raise DistutilsError(msg)
distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('cffi>=1.4.1')
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-hWz7Jg/pynacl/
You are using pip version 9.0.3, however version 10.0.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
[root@ansible1 Python-2.7.9]#
wet https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz
tar -xf Python-2.7.9.tar.xz
[root@ansible1 opt]# tar -xf Python-2.7.9.tar.xz
tar (child): xz:无法 exec: 没有那个文件或目录
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error is not recoverable: exiting now
[root@ansible1 opt]# yum install xz* -y
[root@ansible1 opt]# tar -xf Python-2.7.9.tar.xz
[root@ansible1 opt]# cd Python-2.7.9
[root@ansible1 Python-2.7.9]#
[root@ansible1 Python-2.7.9]# ./configure
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking for --enable-universalsdk... no
checking for --with-universal-archs... 32-bit
checking MACHDEP... linux2
checking EXTRAPLATDIR...
checking for --without-gcc... no
checking for gcc... no
checking for cc... no
checking for cl.exe... no
configure: error: in `/opt/Python-2.7.9':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
[root@ansible1 Python-2.7.9]# yum install gcc gcc-c++ -y
[root@ansible1 Python-2.7.9]#
[root@ansible1 Python-2.7.9]# ./configure
[root@ansible1 Python-2.7.9]# make
[root@ansible1 Python-2.7.9]# make all
[root@ansible1 Python-2.7.9]# make install
[root@ansible1 Python-2.7.9]# make clean
[root@ansible1 Python-2.7.9]# make distclean
查看版本信息
#/usr/local/bin/python2.7 -V
.建立软连接,使系统默认的python指向Pytho2.7
mv /usr/bin/python /usr/bin/python2.6.6
ln -s /usr/local/bin/python2.7 /usr/bin/python
8.解决系统 Python 软链接指向 Python2.7 版本后,因为yum是不兼容 Python 2.7的,所以yum不能正常工作,我们需要指定 yum 的Python版本
vi /usr/bin/yum
1. 将文件头部的
2. #!/usr/bin/python
3. 改成
4. #!/usr/bin/python2.6
[html] view plain copy print?
1. 下载安装脚本
2.
3. #wget --no-check-certificate https://bootstrap.pypa.io/get-pip.py
4.
5. 安装
6.
7. #python get-pip.py
8. copy pip脚本到bin(可以先检查是否已经存在pip命令
9.
10. #cp /usr/local/bin/pip2.7 /usr/bin/pip
11. #pip install ansible --upgrade
[root@ansible1 Python-2.7.9]# python ./get-pip.py
Traceback (most recent call last):
File "./get-pip.py", line 20636, in <module>
main()
File "./get-pip.py", line 197, in main
bootstrap(tmpdir=tmpdir)
File "./get-pip.py", line 82, in bootstrap
import pip._internal
zipimport.ZipImportError: can't decompress data; zlib not available
[root@ansible1 Python-2.7.9]# yum reinstall zlib*
1、安装依赖zlib、zlib-devel
2、重新编译安装Python
1. ./configure
2. 编辑Modules/Setup文件
3. 找到下面这句,去掉注释
4. #zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz
5. 重新编译安装:make & make install
[root@ansible1 Python-2.7.9]# python get-pip.py
Collecting pip
Downloading pip-10.0.0-py2.py3-none-any.whl (1.3MB)
100% |████████████████████████████████| 1.3MB 496kB/s
Collecting setuptools
Downloading setuptools-39.0.1-py2.py3-none-any.whl (569kB)
100% |████████████████████████████████| 573kB 538kB/s
Collecting wheel
Downloading wheel-0.31.0-py2.py3-none-any.whl (41kB)
100% |████████████████████████████████| 51kB 428kB/s
Installing collected packages: pip, setuptools, wheel
Successfully installed pip-10.0.0 setuptools-39.0.1 wheel-0.31.0
[root@ansible1 Python-2.7.9]#
[root@ansible1 Python-2.7.9]# cp /usr/bin/pip /usr/bin/pip_old
[root@ansible1 Python-2.7.9]# cp /usr/local/bin/pip2.7 /usr/bin/pip
cp:是否覆盖"/usr/bin/pip"? y
[root@ansible1 Python-2.7.9]#
(2)SSL没有安装,报错如下:
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting pip
Could not fetch URL https://pypi.python.org/simple/pip/: There was a problem confirming the ssl certificate: Can't connect to HTTPS URL because the SSL module is not available. - skipping
Could not find a version that satisfies the requirement pip (from versions: )
No matching distribution found for pip
解决方案如下:
[root@localhost ~]# python2.7.5
Python 2.7.5 (default, Jun 3 2013, 11:08:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/python27/lib/python2.7/ssl.py", line 60, in <module>
import _ssl # if we can't import it, let the error propagate
ImportError: No module named _ssl
>>>
2. 查看openssl安装包,发现缺少openssl-devel包
[root@localhost ~]# rpm -aq|grep openssl
openssl-0.9.8e-20.el5
openssl-0.9.8e-20.el5
[root@localhost ~]#
3. yum安装openssl-devel
[root@localhost ~]# yum install openssl-devel -y
#查看安装结果
[root@localhost ~]# rpm -aq|grep openssl
openssl-0.9.8e-26.el5_9.1
openssl-0.9.8e-26.el5_9.1
openssl-devel-0.9.8e-26.el5_9.1
openssl-devel-0.9.8e-26.el5_9.1
4. 重新编译python
#修改Setup文件
vi /usr/software/Python-2.7.5/Modules/Setup
#修改结果如下:
# Socket module helper for socket(2)
_socket socketmodule.c timemodule.c
# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
_ssl _ssl.c \
-DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
-L$(SSL)/lib -lssl -lcrypto
5. 重新编译
make
make install
6. 测试,已可正常使用。
[root@localhost ~]# python2.7.5
Python 2.7.5 (default, Jun 3 2013, 14:56:13)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ssl
>>>
ssh-copy-id 10.0.0.1
echo “10.0.0.1” >> /etc/ansible/hosts
ansible all -m ping
ansible 2 以上版本su
[root@ansible1 ~]# ansible test -b --become-method=su --ask-become-pass -m shell -a "id"
SU password:
zhn@127.0.0.1 | SUCCESS | rc=0 >>
uid=0(root) gid=0(root) 组=0(root) 环境=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
利用ssh跳板机访问目标网段
[root@ansible1 ~]# cat /root/.ssh/config
Host 130.51.11.*
IdentityFile=/root/.ssh/lan
ProxyCommand ssh toptea@132.120.2.5 -W %h:%p
ServerAliveInterval 30
ControlMaster no
ControlPath /tmp/%r@%h-%p.ssh
ControlPersist 600
[root@ansible1 ~]#
[root@ansible1 zhn]# cat /etc/ansible/hosts
unionmon@132.98.23.56 ansible_su_pass=Dc_ds9856
[root@ansible1 zhn]# ansible unionmon@132.98.23.56 -b --become-method=su -m shell -a 'id'
unionmon@132.98.23.56 | SUCCESS | rc=0 >>
uid=0(root) gid=0(root) 组=0(root)
playbook使用
[root@ansible ansible]# cat pyhton.yaml
---
- name: install python27
hosts: 130.51.1.113
remote_user: toptea
gather_facts: false
become: yes
become_method: su
become_user: root
tasks:
- name: tar python.tgz
raw: cd /tmp;tar -zxvf Python-2.7.14.tgz
- name: install Python27
raw: cd /tmp/Python-2.7.14;./configure ; make&& make install
- name: create softlink to python
raw: mv /usr/bin/python /usr/bin/pythonbak-1 ;ln -s /usr/local/bin/python2.7 /usr/bin/python
- name: yum env
raw: sed -ibak '1d' /usr/bin/yum ; sed -i '1i\#!/usr/bin/python2.4' /usr/bin/yum
commad模块跟shell模块区别
shell ssh远程会开一个终端bash再执行命令
command 模块不会再bash下执行不 在sshd下执行
bash功能不能用
管道输入bash功能
ansible
ansible hosts –m yum –a ‘name=tree,ksh state=installd’
ansible hosts –m yum –a ‘name=tree,ksh state=removed’
name包名 state 装包还是卸包
ansible hosts –m systemed –a ‘name=chronyd state=stopped’
name= state=
ansible –doc modulename
/usr/lib/python2.7/site-packages/ansible
play-book(yaml文件)
在playbook文件中提前定义一系列的任务
playbook由一个或多个play组成
play中的hosts,variables.roles,tasks等对象都使用键值表示(冒号分割)
Targe:定义要执行playbook运行时需要的变量
Tasks:定义要在远程主机上执行的任务列表
Handler:定义task任务完成后需要调用的任务
Playbook输出结果使用Json格式输出。
yaml格式
空格表示结构
使用-表示数组(横线后面有一个空格)
使用:表示键值(冒号后面有一个空格)
一般每个缩进级别由2个及以上空格组成(不要使用tab)
空格的缩进级别必须对齐
yaml文件 开始行都应该是---三条横线(表示文件开始,不是必须的.但是约定俗称都是这样)
#表示注释
键值:
诗人: 李白
数组:
诗人:
- 李白
- 杜甫
- 白居易
诗人:
- A
姓名: 李白
年代: 唐代
- B
姓名: value
年代: value
开放式数据交换格式(文本)yaml
数据
程序支持
json格式
是纯文本文件
单引号’’字符
[]是表示数组 [‘test’,’hello’,’world’]
{}是键值,使用:分隔 {‘key’:’value’,’name’:’tom’}
()对象分组
,.分隔符,没有顺序
json示例
{ ‘诗人‘:
[‘李白’,’杜甫’,’白居易’]
}
{ ‘诗人‘:
[{‘李白’:’诗仙’,’年代’,’唐’},
{‘杜甫’:’诗圣’,’年代’:’唐’},
{‘白居易‘:’诗魔’,”年代”:’唐’}
]
}
#---
-hosts: node
remote_user: root
tasks:
-name: add user
user: hello1
uid: 1040
group: root
-name: chage pass
shell: echo”123”| passwd –stdin hello1
-shell: chage –d ,0 hello1
python-jinja2
#---
-hosts: node
remote_user: root
vars:
user: hello4
group: root
uid: 1044
tasks:
-name: add user
user:
name: “{{user.name}}”
uid: “{{user.uid}}”
group: “{{user.group}}”
-name: chage pass
shell: echo”123”| passwd –stdin “{{user.name}}”
-shell: chage –d ,0 “{{user.name}}”
ansible-playbook –e参数可以传递不用的变量
‘{“user“:{“name”:”user”,”group”:”root”}}‘
重复利用playbook文件的另一种方式
vi var,user
user:
name: “user3”
group: “root”
ansible-playbook test.yaml –e ‘@var.user‘
COMMENTS | NOTHING