“Ansible基础”与“Ansible安装k8s”:页面之间的差异

来自linuxsa wiki
(页面间差异)
跳转到导航 跳转到搜索
Evan留言 | 贡献
 
Evan留言 | 贡献
 
第1行: 第1行:
= [[Playbook |playbook双击跳转]]=
==
[æn; ən
= 自动化管理大批量服务器=
分组


大规模服务器管理优化
=reference=
[https://blog.csdn.net/rudolfyan/article/details/112341749  ansible 安装k8s 详细步骤]


[defaults]
[https://blog.csdn.net/weixin_44753738/article/details/120619617  通过ansible部署k8s(containerd)]
forks = 50  # 默认是 5


- name: 批量部署
https://github.com/zhushilu/k8s-ansible
  shell: "sleep 300"
  async: 600
  poll: 10




拉取模式(Pull Mode):适合大规模集群,Ansible 默认是 Push 模式,可以使用 ansible-pull
[[category:ansible]] [[category:k8s]]
ansible-pull -U https://github.com/myrepo/playbooks.git -i inventory
 
使用 fact caching 加速执行
[defaults]
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_facts
 
=进阶=
 
[https://blog.51cto.com/u_10272167/2707282 Ansible 日常使用技巧 - 运维总结]
 
[https://blog.jairmir.com/index.php/2021/03/27/ansible%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4/ ansible自动化运维]
 
 
[https://ansible-tran.readthedocs.io/en/latest/docs/intro_getting_started.html  Ansible中文权威指南 ]
 
[https://www.jianshu.com/p/0326780d05fc 2021-Ansible学习]
 
[https://blog.csdn.net/weixin_43798031/article/details/115866901  ansible playbook初始化系统基础环境,直接就可以用]
 
[https://blog.51cto.com/u_13520779/2091782  ansible批量部署服务]
 
[https://zhuanlan.zhihu.com/p/149499486 ansible的安装和操作,并编写一个docker部署的示例]
 
[https://blog.csdn.net/weixin_43748870/article/details/88682689  ansible-playbook使用实例(分发文件,执行脚本)]
 
[https://www.cnblogs.com/LiuChang-blog/p/14702939.html  Ansible自动化运维应用实战 ]
 
[https://blog.csdn.net/u013613428/article/details/92837916  手把手教你在python中运行ansible-playbook]
 
[https://blog.csdn.net/weixin_46833747/article/details/108441827 知识总结(17)ansible总结(ansible的优点、架构、工作原理、常用模块、playbook详解)]
 
[https://www.youtube.com/watch?v=xRMPKQweySE  youtube.com  ansible 100seconds]
 
==变量==
<pre>
vars:
  key_file: /etc/nginx/ssl/nginx.key
 
play book
- name: copy TLS key
  copy: src=files/nginx.key dest={{key_file}} owern=root  mode=0600
 
</pre>
== Chapter 2 inventory==
p48
 
 
[https://www.jianshu.com/p/7eb4c8ee8e13 Ansible教程 第三章 Inventory详解]
 
=introduction=
Ansible是一种IT自动化工具。它可以配置系统,部署软件以及协调更高级的IT任务,例如持续部署,滚动更新。Ansible适用于管理企业IT基础设施,从具有少数主机的小规模到数千个实例的企业环境。Ansible也是一种简单的自动化语言,可以完美地描述IT应用程序基础结构。
 
Ansible is a suite /swiːt/ of software tools that enables infrastructure /ˈɪn.frəˌstrʌk.tʃɚ/ as code. It is open-source and the suite includes software provisioning, configuration management, and application deployment functionality /ˌfʌŋk.ʃənˈæl.ə.t̬i
 
=ins=
https://docs.ansible.com/ansible/latest/installation_guide/index.html
<pre>
#on master  在debian 11上 用pip3 安装的版本很新 不过也是没默认配置文件  自己动手吧
pip3 install --user ansible
 
ssh-copy-id  -i  id_ecdsa.pub root@192.168.88.50
ssh-copy-id  -i  id_ecdsa.pub root@192.168.88.51
ssh-copy-id  -i  id_ecdsa.pub root@192.168.88.52
 
 
 
mkdir  /etc/ansible
vi /etc/ansible/hosts
 
192.168.88.50
192.168.88.51
192.168.88.52
 
[intra]
192.168.10.120
192.168.10.121
 
ansible  all  -b -u root  -a "hostname"
192.168.88.51 | CHANGED | rc=0 >>
k8s-node1
192.168.88.50 | CHANGED | rc=0 >>
k8s-master
192.168.88.52 | CHANGED | rc=0 >>
k8s-node2
 
 
ansible all -m ping
 
</pre>
== ins on centos  use yum  ==
<pre>
yum install epel-release
yum install ansible
</pre>
 
=配置文件=
<pre>
#放自己home更加爽
/home/evan/ansible
 
so  Jul 04  2023
 
sudo vi /etc/ansible/ansible.cfg
[defaults]
inventory = /home/evan/ansible/inventory/hosts
 
 
 
 
# 写在自己的home目录
ansible在使用配置文件时按照以下顺序优先配置:
 
export ANSIBLE_CONFIG
 
./ansible.cfg
 
~/.ansible.cfg
 
/etc/ansible/ansible.cfg
 
如果以上顺序没有找到配置文件ansible会自动使用默认配置
 
关于ansible的配置在/etc/ansible/ansible.cfg文件中,所以关于ansible运行时所使用的ssh配置也可以在此文件中配置。在目前的ansible中,运行ansible时会依次加载 环境变量ANSIBLE_CONFIG,当前目录的ansible.cfg,~/.ansible.cfg,/etc/ansible/ansible.cfg,针对同一个配置项以最先加载到的为准。所以,我们可以单独编写自己的ansible.cfg文件放在当前目录下。
 
可以去github上把默认配置拿下来:
 
https://raw.githubusercontent.com/ansible/ansible/devel/examples/ansible.cfg
# To generate an example config file (a "disabled" one with all default settings, commented out):
#              $ ansible-config init --disabled > ansible.cfg
 
# Also you can now have a more complete file by including existing plugins:
# ansible-config init --disabled -t all > ansible.cfg
 
把它放到/etc/ansible/目录
</pre>
==ansible指定用户 ==
<pre>
方案1:
nsible -m ping -u 用户名
 
方案2:
 
修改/etc/ansible/hosts文件:
[test_hosts]
host_ip ansible_user=用户名
# 还可以指定登陆密码
host_ip ansible_user=用户名 ansible_ssh_pass=登陆密码
 
</pre>
 
=日常技巧=
==sudo ==
 
[https://github.com/evan886/my-ansible/tree/main/sudo-insdocker/ansible sudo 详细例子insdocker在github]
=== 没密码的sudo===
<pre>
cat /etc/ansible/agent.yml
---
- hosts: all
  become: yes
  become_method: sudo
  remote_user: evan 
  #remote_user: ops
  roles:
    - ag_conf
 
#当然 shell 里面也要写sudo
 
#直接在commond 这样执行,要交互,但是可以直接回车 如果没密码
ansible  tmp -m  command -a "ls /root"  -u  evan --become  --ask-become-pass
 
</pre>
[https://blog.51cto.com/u_3379770/1906326  ansible 普通用户执行命令]
 
 
[https://www.cnblogs.com/fjping0606/p/6952749.html  Ansible 使用普通用户远程执行playbook ]
 
https://serverfault.com/questions/870951/ansible-adhoc-command-execute-with-sudo
 
https://stackoverflow.com/questions/38958333/how-to-achieve-sudo-su-user-and-run-all-command-in-ansible#38965192
 
==SSH authenticity checking  ==
<pre>
Is there a way to ignore the SSH authenticity checking made by Ansible? For example when I've just setup a new server I have to answer yes to this question:
 
GATHERING FACTS ***************************************************************
The authenticity of host 'xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx)' can't be established.
RSA key fingerprint is xx:yy:zz:....
Are you sure you want to continue connecting (yes/no)?
 
 
方法1 直接在命令行 加参数
ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook  ssh-u-conf.yml
 
方法2  加到配置文件
/etc/ansible/ansible.cfg or ~/.ansible.cfg
 
[defaults]
host_key_checking = False
 
</pre>
https://stackoverflow.com/questions/32297456/how-to-ignore-ansible-ssh-authenticity-checking
==分组==
ansible beta -b -u evan -m shell  -a " sudo hostname"
执行ansible-playbook  -C /etc/ansible/agent.yml 得在 yml 里面指定 hostip etc
 
<pre>
inventory 文件hosts
 
# 非标准的22端口 必须第一列为别外 不然无效哦 January 24 2022
[add]
#172.16.0.40
[beta]
beta-insurance ansible_host=172.16.0.14  ansible_port=22
[pro]
prod-core-mongo                ansible_host=172.16.1.40  ansible_port=22
prod-access                    ansible_host=172.16.1.8  ansible_port=22
prod-insurance-backstage      ansible_host=172.16.0.16  ansible_port=22
prod-insurance-crm-mongo      ansible_host=172.16.1.37  ansible_port=22 
prod-insurance-backstage-count ansible_host=172.16.1.19  ansible_port=22
prod_core                      ansible_host=172.16.1.9 ansible_port=22
prod_mq                        ansible_host=172.16.1.12 ansible_port=22
 
[core]
prod_core
prod-core-mongo
 
[insure]
prod-access
prod-insurance-backstage
prod-insurance-crm-mongo
prod-insurance-backstage-count
 
</pre>
 
== run shell==
#还是 -m shell 好用, -m script 不太好用感觉
ansible core  -b -u evan -m shell  -a "sudo ls /home/evan"
  ansible insure -m shell  -a "sudo cat /etc/ssh/sshd_config | grep Permit"
 
== 常用参数==
-m MODULE_NAME #执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
-u REMOTE_USER #远程用户,默认为 root 用户
 
查看列表的命令
-m 要执行的模块,默认为command
-a 模块的参数
-u ssh连接的用户名,默认用root,ansible.cfg中可以配置
-C, --check          don't make any changes; instead, try to predict some
                        of the changes that may occur
 
==变量==
<pre>
# 主机和主机组变量(主机变量优先级大于主机组变量)
 
vim /etc/ansible/hosts
 
[webservers]
 
172.16.1.121:22 ansible_ssh_user=root ansible_ssh_pass='123456' http_port=80
 
172.16.1.122:22 ansible_ssh_user=root ansible_ssh_pass='123456'
 
 
[webservers:vars]
http_port=8080
server_name=www.baidu.com
 
实验:
 
ansible webservers -m command -a "echo {{http_port}}" -o
 
命令说明:
 
ansible webservers -m command -a "echo {{http_port}}" -o
 
ansible:ansible命令
 
webservers:/etc/ansible/hosts中配置的主机组名称,指定 all (分组和未分组的主机)代表所有主机,指定172.16.1.121代表单台主机。
 
-m:指定使用的模块,默认是command模块(简单的shell命令),可以省略不写。
 
-a:指定具体使用的shell指令,比如"echo {{http_port}}"表示在远程主机上打印http_port这个变量。
 
-o:对ansible的输出的结果进行压缩(即,输出的结果显示在一行)
 
ansible-playbook  pvar.yml
 
PLAY [Example playbook with variables] *********************************************************************
 
TASK [Gathering Facts] *************************************************************************************
ok: [192.168.10.74]
ok: [192.168.10.93]
 
TASK [Print variables] *************************************************************************************
ok: [192.168.10.74] => {
    "msg": "HTTP port is 80 and max clients is 200"
}
ok: [192.168.10.93] => {
    "msg": "HTTP port is 80 and max clients is 200"
}
 
PLAY RECAP *************************************************************************************************
192.168.10.74              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
192.168.10.93              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
 
➜  tmp cat  pvar.yml
---
- name: Example playbook with variables
  hosts: '2025'
  vars:
    http_port: 80
    max_clients: 200
  tasks:
    - name: Print variables
      debug:
        msg: "HTTP port is {{ http_port }} and max clients is {{ max_clients }}"
 
 
 
 
 
 
</pre>
 
==远程执行shell脚本文件 ==
=== Friday July twenty-ninth 2022===
===编写脚本  ===
<pre>
cat /tmp/mypatch
# 卸载旧版本
yum remove -y kubelet kubeadm kubectl
 
# 安装kubelet、kubeadm、kubectl
# 将 ${1} 替换为 kubernetes 版本号,例如
v=1.21.12
yum install -y kubelet-${v} kubeadm-${v} kubectl-${v}
crictl config runtime-endpoint /run/containerd/containerd.sock
# 重启 docker,并启动 kubelet
systemctl daemon-reload
systemctl enable kubelet && systemctl start kubelet
 
</pre>
=== 脚本copy到其他几台服务器===
<pre>
#执行ansible命令,将脚本copy到其他几台服务器上
  ansible  myk8s -u root -m copy -a "src=/tmp/mypatch dest=/tmp/mypatch"
 
</pre>
===每台服务器上执行 你的shell脚本 ===
<pre>
#执行ansible命令,在每台服务器上执行 你的shell脚本
ansible  myk8s -u root -m shell -a "bash /tmp/mypatch chdir=/tmp"
 
</pre>
[https://blog.51cto.com/llzdwyp/1761057  3.4-ansible远程执行脚本]
 
==ansible 常用模块==
===主机连通性测试===
<pre>
 
ansible-doc ping
 
ansible web -m ping命令来进行主机连通性测试
 
  ansible ansible mytmp -m ping
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was 127.0.0.1
127.0.0.1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
</pre>
 
=== command 模块===
<pre>
ansible web -m command -a 'ss -ntl'
 
命令模块接受命令名称,后面是空格分隔的列表参数。给定的命令将在所有选定的节点上执行。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";","&" 工作(需要使用(shell)模块实现这些功能)。注意,该命令不支持| 管道命令。
  下面来看一看该模块下常用的几个命令:
 
    chdir       # 在执行命令之前,先切换到该目录
    executable # 切换shell来执行命令,需要使用命令的绝对路径
    free_form   # 要执行的Linux指令,一般使用Ansible的-a参数代替。
    creates  # 一个文件名,当这个文件存在,则该命令不执行,可以
    用来做判断
    removes # 一个文件名,这个文件不存在,则该命令不执行
 
</pre>
===shell 模块===
<pre>
shell模块基本和command相同,但是shell raw支持管道符
 
➜  ~ ansible pi3 -m raw -a "cat /etc/passwd | wc -l"
192.168.10.5 | CHANGED | rc=0 >>
41
Shared connection to 192.168.10.5 closed.
 
➜  ~ ansible pi3 -m shell  -a "cat /etc/passwd | wc -l"
192.168.10.5 | CHANGED | rc=0 >>
41
 
 
 
shell > ansible Client -m shell -a "/home/test.sh"          # 执行远程脚本
 
 
cat /root/2
touch 2.txt
 
ansible 200  -b -u evan -m shell  -a  "sudo bash  /home/evan/close"
 
# cat /home/evan/2.txt 用sudo 默认去了 evan
</pre>
 
===copy 模块===
  ansible  myk8  -m copy -a 'dest=/home/evan src=/tmp/vboxdrv-Module.symvers'  #把 master上的 /tmp/vboxdrv-Module.symvers  cp到 myk8组的所有机器的 /home/evan下
 
===fetch 模块===
和copy 相反 ,可看作文件上传动作,  把 远端机器的 /home/evan/vboxdrv-Module.symvers 收集回主机的 /home/evan/tmp/tpp目录下
  ansible  myk8 -m fetch -a 'dest=/home/evan/tmp/tpp  src=/home/evan/vboxdrv-Module.symvers'
 
==== file ====
还有相关的什么权限 用户组 属性什么的
ansible  myk8  -m file -a  'path=/home/evan/vboxdrv-Module.symvers  state=absent' #删除/home/evan/vboxdrv-Module.symvers
 
===9)service 模块===
 
<pre>
该模块用于服务程序的管理。
  其主要选项如下:
 
    arguments #命令行提供额外的参数
    enabled #设置开机启动。
    name= #服务名称
    runlevel #开机启动的级别,一般不用指定。
    sleep #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。(定义在剧本中。)
    state #有四种状态,分别为:started--->启动服务, stopped--->停止服务, restarted--->重启服务, reloaded--->重载配置
 
  下面是一些例子:
① 开启服务并设置自启动
 
[root@server ~]# ansible web -m service -a 'name=nginx state=started enabled=true'
</pre>
 
===12)script 模块 运行sh or py 2023 update===
<pre>
script模块将控制节点的脚本执行在被控节点上。 相当于scp+shell
 
➜  ~ hostname
myxps
➜  ~ cat /tmp/hostname
hostname
➜  ~
➜  ~ ansible pi3 -m  script -a /tmp/hostname
192.168.10.5 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 192.168.10.5 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 192.168.10.5 closed."
    ],
    "stdout": "mypi3b\r\n",
    "stdout_lines": [
        "mypi3b"
    ]
}
➜  ~
 
 
 
 
  一般用在被管主机上 执行一系列命令就非常爽
一般先用copy 把脚本下发到所有的 slave机器 再执行
 
#Dec thirteenth 2022
 
ansible的script模块的用途
 
script 模块用来在远程主机上执行 ansible 管理主机上的脚本,
 
即:脚本一直存在于 ansible 管理主机本地,
 
不需要手动拷贝到远程主机后再执行
 
➜  tmp cat a.sh
touch  evantouch.txt
 
chmod +x /home/evan/tmp/a.sh
 
ansible intra  -u root  -m  script -a '/home/evan/tmp/a.sh'
 
ansible intra    -m  script -a '/home/evan/tmp/a.sh' --become  --become-method=sudo --become-user=root
执行效果
-192-168-10-121-c7 ~] {16:35:22} (0)
# ls /root/evantouch.txt
/root/evantouch.txt
 
 
根据文件判断是否需要执行脚本?
 
creates参数 :使用此参数指定一个远程主机中的文件,当指定的文件存在时,就不执行对应脚本
removes参数 :使用此参数指定一个远程主机中的文件,当指定的文件不存在时,就不执行对应脚本
 
[root@centos8 ~]# ansible yujian -m script -a 'removes=/root/isgit.txt /home/liuhongdi/ansible/gitpubwww.sh'  --become  --become-method=sudo --become-user=root
121.122.123.47 | SKIPPED
 
因为删除文件不成功,所以不执行
 
[root@centos8 ~]# ansible yujian -m script -a 'creates=/root/isgit.txt /home/liuhongdi/ansible/gitpubwww.sh'  --become  --become-method=sudo --become-user=root
121.122.123.47 | CHANGED => {
    "changed": true,
...
 
因为文件可以创建,所以成功执行
 
 
 
 
 
万事先man
 
root@myxps:~# ansible-doc  -s script
- name: Runs a local script (shell and py etc) on a remote node after transferring it
  script:
      chdir:                # Change into this directory on the remote node before
                              running the script.
      cmd:                  # Path to the local script to run followed by optional
                              arguments.
      creates:              # A filename on the remote node, when it already
                              exists, this step will
                              *not* be run.
      decrypt:              # This option controls the autodecryption of source
                              files using vault.
      executable:            # Name or path of a executable to invoke the script
                              with.
      free_form:            # Path to the local script file followed by optional
                              arguments.
      removes:              # A filename on the remote node, when it does not
                              exist, this step will
                              *not* be run.
 
 
[evan@ ansible]$ ansible add -m script -a './1.sh'
 
[evan@ ansible]$ cat  1.sh
touch /tmp/byevanjan.log
 
 
py
 
evan@debian-s-1vcpu-1gb-sfo2-01:~$ ansible ec2  -m script -a ' ./getip.py'
 
ec2 | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to 54.215.65.27 closed.\r\n",
    "stderr_lines": [
        "Shared connection to 54.215.65.27 closed."
    ],
    "stdout": "54.215.65.27\r\n",
    "stdout_lines": [
        "54.215.65.27"
    ]
}
 
 
cat getip.py
#!/usr/bin/python3
import requests
print(requests.get('http://ifconfig.me/ip', timeout=1).text.strip())
 
 
</pre>
 
[https://www.cnblogs.com/architectforest/p/12766206.html ansible的script模块的用途]
 
https://blog.51cto.com/noodle/1769474
 
[https://qa.icopy.site/questions/35139711/running-python-script-via-ansible 通过 ansible 运行 Python 脚本]
 
===stat 模块===
  ansible sftp -m stat  -a "path=/etc/passwd"
 
===firewalld模块===
<pre>
 
service : Name of a service to add/remove to/from firewalld.The service must be listed in output of firewall-cmd --get-services.
指定放行的服务,此服务必须要在firewall-cmd --get-services查询的到。
 
irewalld模块主要设置火墙对服务和端口的允许
参数:ansible-doc -s firewalld查看一下fetch模块的参数`
 
service参数 必须参数,用于指定要允许服务。
state参数 enabled开机启动
permanent参数 true 永久添加
immediate参数 true 立即生效
 
 
 
 
 
 
 
 
#  firewall-cmd --list-all
public
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: dhcpv6-client ssh
 
 
  /etc/ansible# cat fire.yml
---
- hosts: 192.168.10.122
  gather_facts: true
  remote_user: root
  tasks:
  - name: "firewalld"
    firewalld:
      service: http
      state: enabled
      permanent: true
      immediate: yes
     
     
ansible-playbook -C  fire.yml
ansible-playbook  fire.yml
     
运行后 结果如下 多了个 http
 
firewall-cmd --list-all
public
  target: default
  icmp-block-inversion: no
  interfaces:
  sources:
  services: dhcpv6-client http ssh
 
 
#直接执行
ansible node1 -m firewalld -a 'service=https permanent=yes state=enabled'
 
 
 
ansible node1 -m service -a 'name=firewalld state=restarted'
 
 
#建议reload 不要动不动restart
ansible intra -m service -a 'name=firewalld state=reloaded'
 
 
ansible intra -m firewalld -a 'port=8081/tcp permanent=yes state=enabled'
</pre>
 
[https://www.cnblogs.com/hypj/p/14035206.html ansible firewalld模块详解]
===[[ansible包管理模块]]请双击跳转===
 
===ansible 用户批量创建与管理===
<pre>
 
最笨的办法  明显不是我们要的
ansible intra -m command -a 'useradd appl'
 
 
ansible-doc  user -s
 
 
最好的办法  playbook
 
/etc/ansible# cat adduser.yml
---
- hosts: all
  remote_user: root
  tasks:
  - name: 'Create  group lai'
    group:
    name: lai
    state: present       
 
  - name: create user deployer
    user:
      name: "{{ item.user }}"
      group: "{{ item.user }}"
      password: "{{ item.pass|password_hash('sha512') }}"
      state: present
      update_password: on_create
    loop:
        - { user: lai , pass:  '2240881'}   
 
#密码要用字符
 
 
 
</pre>
 
=Ansible-Playbook之初始化服务器=
<pre>
init-user
init-tools
 
vim task/main.yml
- include: user.yml  #用户管理
- include: repo.yml  #yum源
- include: init_pkg.yml  #安装基础组件
- include: profile.yml  #环境变量
- include: selinux.yml  #selinux
- include: dir.yml  #基础目录
- include: limits.yml  #系统参数
- include: iptables.yml  #防火墙
- include: sysctl.yml  #内核参数
- include: rc.local.yml  #开机启动
- include: dns.yml    #dns
- include: ntp.yml    #ntp
- include: rsyslog.yml  #日志同步
- include: sshd.yml  #ssh优化
- include: safe.yml  #安全配置
 
</pre>
 
[https://juejin.cn/post/6995171921004331038  good-ansible自动化:操作系统初始化具体实现 ]
 
[https://cloud.tencent.com/developer/article/1702876 03 实战 Ansible-Playbook之初始化服务器--有sshd安全相关]
 
https://gitee.com/wanghui1234/ansible_repo
 
[https://blog.csdn.net/weixin_30955341/article/details/101262866  ansible-playbook编写服务器初始化脚本]
==Ansible-Playbook 修改ssh 配置举例 ==
 
<pre>
 
cat /etc/ansible/ssh-u-conf.yml
---
- hosts: add
  become: yes
  become_method: sudo
  gather_facts: true
  remote_user: ubuntu
  #remote_user: root
  tasks:
 
  - name: "Change password"
    user: name={{ item.name }} password={{  item.chpass | password_hash('sha512') }} update_password=always
    with_items:
      - { name: 'root', chpass: 'root1234' }
      - { name: 'evan', chpass: 'evan1234' }
 
 
 
  - name: "修改ssh配置文件的安全选项"
    lineinfile:
      path: /etc/ssh/sshd_config
      regexp: '{{ item.regexp }}'
      line: '{{ item.line }}'
      state: present
    with_items:
      - regexp: "^PasswordAuthentication"
        line: "PasswordAuthentication yes"
      - regexp: "^#PermitRootLogin"
        line: "PermitRootLogin yes"
      #- regexp: "^#Port 22"
      #  line: "Port 2249"
      - regexp: "^GSSAPIAuthentication yes"
        line: "GSSAPIAuthentication no"
    notify:
      - restart sshd
  handlers:
    - name: restart sshd
      service:
        name: sshd
        state: restarted
 
 
 
 
ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook  ssh-u-conf.yml
 
 
 
跑脚本前
evan@ubuntu-2004-1:~$ cat /etc/ssh/sshd_config | grep Per
#PermitRootLogin prohibit-password
 
跑后
evan@ubuntu-2004-1:~$ cat /etc/ssh/sshd_config | grep Per
PermitRootLogin yes
 
#这样就可以用root登录了 在不用太安全的开发环境可用,不过记得u 20.04 要先passwd root
 
</pre>
 
=YAML=
<pre>
➜  ~ cat data.yaml
---
- Apple
- Orange
- Strawbeery
- Mango
➜  ~
 
 
In [3]: with open('data.yaml') as f:
  ...:    print(yaml.safe_load(f))
  ...:
  ...:
['Apple', 'Orange', 'Strawbeery', 'Mango']
 
</pre>
 
=ansible配合shell脚本批量编译安装python3.7=
https://github.com/evan886/my-ansible
 
具体安排脚本here
https://github.com/evan886/my-ansible/tree/main/ansible4py3.7ins
 
<pre>
git clone git@github.com:evan886/my-ansible.git
 
cd ansible4py3.7ins/
 
执行playbook
测试
root@myxps:/etc/ansible# ansible-playbook -C  python.yml
 
执行
root@myxps:/etc/ansible# ansible-playbook  python.yml
</pre>
 
 
 
[https://blog.csdn.net/reblue520/article/details/81301223  ansible配合shell脚本批量编译安装python3.6.6]
 
=ansible配合shell脚本批量安装golang=
 
https://golang.org/doc/install
<pre>
tree
.
├── ansible.cfg
├── go.yml
├── hosts
└── roles
    └── go_install
        ├── files
        │   └── go1.17.1.linux-amd64.tar.gz
        ├── tasks
        │   ├── copy.yml
        │   ├── install.yml
        │   └── main.yml
        └── templates
            └── go_install.sh
 
5 directories, 8 files
 
 
 
reload environment variable.  怎么搞 要手工不成  不科学
oot@myxps:/etc/ansible# ansible intra -b -u root  -a "source /etc/profile"
192.168.10.120 | FAILED | rc=2 >>
[Errno 2] 没有那个文件或目录
192.168.10.121 | FAILED | rc=2 >>
[Errno 2] 没有那个文件或目录
root@myxps:/etc/ansible# ansible intra -b -u root  -a ". /etc/profile"
192.168.10.121 | FAILED | rc=13 >>
[Errno 13] 权限不够
192.168.10.120 | FAILED | rc=13 >>
[Errno 13] 权限不够
 
 
</pre>
 
== run==
<pre>
 
#!/usr/bin/env ansible-playbook
 
加权限后就可以  ./youfile
 
 
root@myxps:/etc/ansible# ansible-playbook -C  go.yml
[WARNING]: ansible.utils.display.initialize_locale has not been called, this may result in incorrectly
calculated text widths that can cause Display to print incorrect line lengths
 
PLAY [all] *****************************************************************************************************
 
TASK [Gathering Facts] *****************************************************************************************
ok: [192.168.10.121]
ok: [192.168.10.120]
 
TASK [go_install : copy go_tgz to client] **********************************************************************
changed: [192.168.10.120]
changed: [192.168.10.121]
 
TASK [go_install : copy install_go_script to client] ***********************************************************
changed: [192.168.10.120]
changed: [192.168.10.121]
 
TASK [go_install : install go] *********************************************************************************
skipping: [192.168.10.120]
skipping: [192.168.10.121]
 
PLAY RECAP *****************************************************************************************************
192.168.10.120            : ok=3    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0 
192.168.10.121            : ok=3    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0 
 
root@myxps:/etc/ansible# ansible-playbook  go.yml
[WARNING]: ansible.utils.display.initialize_locale has not been called, this may result in incorrectly calculated text widths that can cause Display to print incorrect line
lengths
 
PLAY [all] ******************************************************************************************************************************************************************
 
TASK [Gathering Facts] ******************************************************************************************************************************************************
ok: [192.168.10.121]
ok: [192.168.10.120]
 
TASK [go_install : copy go_tgz to client] ***********************************************************************************************************************************
changed: [192.168.10.120]
changed: [192.168.10.121]
 
TASK [go_install : copy install_go_script to client] ************************************************************************************************************************
changed: [192.168.10.120]
changed: [192.168.10.121]
 
TASK [go_install : install go] **********************************************************************************************************************************************
changed: [192.168.10.120]
changed: [192.168.10.121]
 
PLAY RECAP ******************************************************************************************************************************************************************
192.168.10.120            : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
192.168.10.121            : ok=4    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
 
 
</pre>
[https://www.jianshu.com/p/d4e6655ff937 Ansible Role 系统环境 之【go】]
 
=ansible sudo 安装配置docker =
 
==  Ansible Galaxy 搜索 dockek 有空要自己写成galaxy==
https://www.cnblogs.com/sparkdev/p/9962904.html
== 直接使用yum==
<pre>
 
vi install_docker-ce.yml
---
- hosts: docker
  remote_user: root
  tasks:
    - name: install yum-utils
      yum: name=yum-utils state=present
    - name: add docker repo
      shell: yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    - name: install docer-ce
      yum:
        name: docker-ce
        state: present
    - name: install docker-ce-cli
      yum:
        name: docker-ce-cli
        state: present
    - name: install containerd.io
      yum:
        name: containerd.io
        state: present
    - name: config mirro
      copy: src=~/docker-daemon.json dest=/etc/docker/daemon.json
      tags: configmirro
    - name: start enable docker
      service: name=docker state=started enabled=true
    - name: restrat
      shell: sudo systemctl daemon-reload && sudo systemctl restart docker
      tags: restart
 
#mirror配置
cat docker-daemon.json
{
  "registry-mirrors": [
    "https://registry.docker-cn.com",
    "http://hub-mirror.c.163.com",
    "https://docker.mirrors.ustc.edu.cn"
  ]
}
 
 
4.运行playbook
 
ansible-playbook -v install_docker-ce.yml
 
 
 
</pre>
 
==比较全面的 playbook and roles ==
https://github.com/evan886/my-ansible/tree/main/sudo-insdocker/ansible
 
=ansible sudo 安装配置zbx agent =
https://github.com/evan886/my-ansible
 
#具体脚本
https://github.com/evan886/my-ansible/tree/main/ansible4zbxagent-insconf
 
=ansible sudo 修改ssh配置文件的安全选项 =
<pre>
Attention
如果有 多个 PasswordAuthentication yes 可能不成功 只改了一个为no
 
cat modify_sshd.yml
---
- hosts: cor
#- hosts: all
  gather_facts: true
  #remote_user: root
  become: yes
  become_method: sudo
  remote_user: evan
 
  tasks:
  - name: "修改ssh配置文件的安全选项"
    lineinfile:
      path: /etc/ssh/sshd_config
      regexp: '{{ item.regexp }}'
      line: '{{ item.line }}'
      state: present
    with_items:
      - regexp: "^PasswordAuthentication"
        line: "PasswordAuthentication no"
      - regexp: "^#PermitRootLogin yes"
        line: "PermitRootLogin no"
      - regexp: "^PermitRootLogin yes"
        line: "PermitRootLogin no"
 
      #- regexp: "^#Port 22"
      #  line: "Port 2249"
      - regexp: "^GSSAPIAuthentication yes"
        line: "GSSAPIAuthentication no"
    notify:
      - restart sshd
  handlers:
    - name: restart sshd
      service:
        name: sshd
        state: restarted
 
 
 
 
ansible-playbook  modify_sshd.yml
 
直接
ansible all -b  --become-method=su  --become-user-root -m shell -a "sed 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config" |grep -E "Root|172.16"
 
 
2022
 
cat /etc/ansible/hosts
[one]
192.168.10.122
 
 
---
- hosts: one
  gather_facts: true
  remote_user: root
  tasks:
  - name: "修改ssh配置文件的安全选项"
    lineinfile:
      path: /etc/ssh/sshd_config
      regexp: '{{ item.regexp }}'
      line: '{{ item.line }}'
      state: present
    with_items:
      - regexp: "^PasswordAuthentication"
        line: "PasswordAuthentication no"
      - regexp: "^#PermitRootLogin"
        line: "PermitRootLogin yes"
      #- regexp: "^#Port 22"
      #  line: "Port 2249"
      - regexp: "^GSSAPIAuthentication yes"
        line: "GSSAPIAuthentication no"
    notify:
      - restart sshd
  handlers:
    - name: restart sshd
      service:
        name: sshd
        state: restarted
 
 
如果有多个 PasswordAuthentication yes
可能要执行多次 也有可能不成功 注意了
 
ansible-playbook -C ssh-conf.yml
ansible-playbook  ssh-conf.yml
 
</pre>
 
=Ansible使用playbook自动化编译安装Nginx=
 
[https://www.linuxidc.com/Linux/2017-10/148058.htm Ansible使用playbook自动化编译安装Nginx]
 
=ansible 批量修改已存在用户的密码=
<pre>
cat /etc/ansible/change-passwd.yml
---
  - hosts: prod
    become: yes
    become_method: sudo
 
    gather_facts: false
    tasks:
    - name: change user passwd
      user: name={{ item.name }} password={{ item.chpass | password_hash('sha512') }}  update_password=always
      with_items:
          - { name: 'evan', chpass: '$evan1234567' }
 
 
#run test
ansible-playbook -C  change-passwd.yml
#run
ansible-playbook  change-passwd.yml
 
</pre>
 
=ansible 创建用户=
<pre>
useradd jsxge
chown -R jsxge.wheel jsxge
echo "123456" | passwd --stdin jsxge
</pre>
 
[https://www.codenong.com/37333305/ 关于sudoers:Ansible:创建具有sudo特权的用户]
 
=ansible修改hostname modify_hostname=
<pre>
cat hosts
[pro]
172.16.0.8 
172.16.0.16 
172.16.0.37
172.16.0.19
172.16.0.9 
 
ansible]$ cat modify_hostname.yml
---
- name: set hostname
  hosts: pro
  #hosts: all
  become: yes
  become_method: sudo
  remote_user: eva
 
  gather_facts: false
  vars:
    hostnames:
      - host: 172.16.0.8
        name: prod-access
      - host: 172.16.0.16
        name: prod-insurance-backstage
 
      - host: 172.16.0.37
        name: prod-insurance-crm-mongo
      - host: 172.16.0.19
        name: prod-insurance-backstage-count
      - host: 172.16.0.9
        name: prod-insurance-core
  tasks:
    - name: set hostname
      hostname:
        name: "{{item.name}}"
      when: item.host == inventory_hostname
      loop: "{{hostnames}}"
 
 
</pre>
 
=ansible and shell=
 
[https://bingostack.com/2021/03/ansible-shell-command/ 使用ansible执行shell命令的正确姿势]
=ansible-galaxy=
 
== ansible-galaxy install docker==
<pre>  ansible-galaxy install geerlingguy.docker #记得国内机器可能要改dns 为8.8.4.4 不然连接github time out
 
#主要配置文件
root@myxps:~# cat ~/.ansible/roles/geerlingguy.docker/defaults/main.yml
 
 
cat pb-docker.yml  #安装 docker
- hosts: mydocker
  vars:
    docker_users:
      - root
  roles:
    - role: geerlingguy.docker
      become: yes
 
 
ansible-playbook -u root pb_docker.yml
 
</pre>
[https://codeantenna.com/a/wQw1weZj3O 通过 Ansible 安装 Docker]
 
=分发文件=
<pre>
 
cat /etc/ansible/hosts
[intra]
192.168.10.120
192.168.10.121
 
 
 
ansible intra -m copy -a "src=/home/evan/data/devops/node-v14.17.6-linux-x64.tar.xz  dest=/root/"
 
ansible 122 -m copy -a "src=/home/evan/data/devops/jdk/jdk-8u212-linux-x64.rpm dest=/root/"
 
 
</pre>
[https://blog.csdn.net/wszll_Alex/article/details/77688224  ansible批量传输文件]
 
[https://www.cxyzjd.com/article/Jailman/78344245 结合P2P软件使用Ansible分发大文件_神棍之路-程序员宅基地]
 
[https://zdyxry.github.io/2019/11/22/%E4%BD%BF%E7%94%A8-Ansible-%E4%BC%A0%E8%BE%93%E6%96%87%E4%BB%B6%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F/ 使用 Ansible 传输文件的几种方式]
 
=troubleshooting=
 
<pre>
 
TASK [ag_conf : install conig  zbx agent] **************************************************************************
fatal: [172.16.0.16]: FAILED! => {"changed": true, "cmd": "/bin/bash /tmp/i.sh", "delta": "0:00:00.065791", "end": "2021-10-15 10:54:54.896410", "msg": "non-zero return code", "rc": 127, "start": "2021-10-15 10:54:54.830619", "stderr": "/bin/bash: /tmp/i.sh: 没有那个文件或目录", "stderr_lines": ["/bin/bash: /tmp/i.sh: 没有那个文件或目录"], "stdout": "", "stdout_lines": []}
 
PLAY RECAP *********************************************************************************************************
172.16.0.16                : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0 
 
 
solution
忘记main.yml 加上 copy.yml喽
 
 
普通用户 
 
$ ansible
Traceback (most recent call last):
  File "/usr/local/bin/ansible", line 32, in <module>
    from ansible import context
ModuleNotFoundError: No module named 'ansible'
 
 
evan@myxps:~/data/resume/interview$ pip list  | grep ansible
evan@myxps:~/data/resume/interview$ sudo pip list  | grep ansible
ansible                        4.5.0
ansible-core                  2.11.5
 
</pre>
 
 
 
[https://al-cui.github.io/2020/04/05/Ansible-playbook%20%E5%85%B3%E4%BA%8Essh%E7%9A%84%E9%85%8D%E7%BD%AE%E5%92%8C%E4%BD%BF%E7%94%A8/  ansible中配置ssh--ssh连接断开时,如何很快获取异常并中断playbook的执行]
== [DEPRECATION WARNING]: "include" is deprecated, use include_tasks/import_tasks instead. This feature will be removed ==
把你的 tasks/main.yml include 换成  include_tasks/import_tasks 就可以了
 
=Ansible  Vault=
 
==Running Ansible with Vault-Encrypted Files==
 
===Using an Interactive Prompt===
<pre>
 
➜ ansible-vault create secret_key
 
➜  ansible vi  inventory/hosts
#Aug  11  2023
[database]
localhost ansible_connection=local
➜  ansible ansible --ask-vault-pass -bK -m copy -a 'src=secret_key dest=/tmp/secret_key mode=0600 owner=root group=root' localhost
BECOME password:
Vault password:
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was 127.0.0.1
localhost | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "checksum": "15bb6433cbfcba861b6e7c1121fbe097f68ff14f",
    "dest": "/tmp/secret_key",
    "gid": 0,
    "group": "root",
    "md5sum": "e894b01b2cc7fc8f341df858e031798a",
    "mode": "0600",
    "owner": "root",
    "size": 17,
    "src": "/home/evan/.ansible/tmp/ansible-tmp-1691743336.7170281-39285-290202074/source",
    "state": "file",
    "uid": 0
}
 
➜  ansible sudo cat /tmp/secret_key
onfidential data
 
</pre>
 
===Using Ansible Vault with a Password File===
<pre>
echo 'my_vault_password' > .vault_pass
 
 
 
➜  .ansible ls
change-passwd.yml  cp  secret_key  tmp
➜  .ansible ansible --vault-password-file=.vault_pass -bK -m copy -a 'src=secret_key dest=/tmp/secret_key mode=0600 owner=root group=root' localhost
BECOME password:
[WARNING]: A duplicate localhost-like entry was found (localhost). First found localhost was 127.0.0.1
localhost | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "checksum": "478a4b2f4eed95489ca86c7d4f060da80f498202",
    "dest": "/tmp/secret_key",
    "gid": 0,
    "group": "root",
    "md5sum": "ee950cc0624bbba77126274ceb752e3c",
    "mode": "0600",
    "owner": "root",
    "size": 7,
    "src": "/home/evan/.ansible/tmp/ansible-tmp-1691749143.0555234-42774-280022701874123/source",
    "state": "file",
    "uid": 0
 
 
#我又新建议了一个
➜  .ansible sudo cat /tmp/secret_key
dafasf
 
</pre>
 
https://www.digitalocean.com/community/tutorials/how-to-use-vault-to-protect-sensitive-ansible-data
 
https://docs.ansible.com/ansible/latest/vault_guide/vault_managing_passwords.html
 
=see also=
[[Playbook]]
 
[[Ansible包管理模块]]
 
=Galaxy=
 
[https://blog.csdn.net/qq_43584691/article/details/118365603  Ansible 系列之 Galaxy 工具]
 
=ansible: How to avoid warnings=
 
<pre>
vim ~/.ansible.cfg or /etc/ansible/ansible.cfg
 
[defaults]
interpreter_python=auto_silent 
 
</pre>
=References=
 
[https://www.cnblogs.com/sparkdev/p/9905290.html Ansible 简介]
 
[https://www.jianshu.com/p/e390a01669f8 ansible基础教程]
 
 
[https://z.itpub.net/article/detail/BFF69D272DEFB9A5C71F2D8F839B4A93 别让运维太忙,一文详解 Ansible 的自动化运维,提高工作效率]
 
[https://blog.wangriyu.wang/2018/08-Jenkins.html Jenkins + Ansible 实现 Golang 自动化编译部署]
 
https://github.com/apenella/go-ansible#install
 
[https://www.cnblogs.com/f-ck-need-u/p/7567417.html  Ansible系列(四):playbook应用和roles自动化批量安装示例 ]
 
[https://www.gbgj.net/info/468349.html langroot下载 分享Ansible批量安装golang环境]
 
[https://www.cnblogs.com/chenxianpao/p/7360349.html  ansible基本使用教程]
 
[https://blog.csdn.net/dghfttgv/article/details/104726454  Ansible(1)—— Ansible详解及inventory文件配置]
 
[https://juejin.cn/post/7050429548495634469  ansible入门 ]
 
[https://zhuanlan.zhihu.com/p/139846936 一分钟了解Ansible]
 
[https://en.wikipedia.org/wiki/Comparison_of_open-source_configuration_management_software Comparison of open-source configuration management software]
 
[https://blog.csdn.net/ximenjianxue/article/details/115326825  DevOps之Cfengine工具安装过程图解]
 
[[category:devops]][[category:ansible]]

2022年8月18日 (四) 06:55的最新版本