在 Ubuntu 22.04安装配置 Ansible

一、按官网指引安装

我使用的ubuntu22.04版本,使用apt安装。官网指引如下:

$ sudo apt-get install software-properties-common
$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible

由于内部网络需要代理上网,需要在apt配置代理。

sudo export http_proxy=http://192.168.1.1:8080
sudo export https_proxy=http://192.168.1.1:8080

 安装完,reboot重启,并查看版本ansible --version

 在 Ubuntu 22.04安装配置 Ansible_第1张图片

二、设置 SSH 密钥并在被管理节点之间共享

 ssh 无密码认证。在控制节点为用户生成 SSH 密钥,并在被管理主机之间共享。执行 ssh-keygen 命令,执行 ssh-copy-id 命令,在受控主机之间共享 ssh 密钥,示例如下

$ ssh-keygen

$ ssh-copy-id node1.example.com
$ ssh-copy-id node2.example.com

三、ansible命令

1、ansible

语法:ansible  host  options

举例:检查所有主机是否存活,执行命令如下

root@:/etc/ansible# ansible server -m ping
192.168.1.1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
2、Ansible-doc 

Ansible-doc用来查询ansible模块文档的说明,类似于man命令

3、Ansible-playbook

语法格式:ansible-play  playbook.yml

4、Ansible-console

Ansible-console是Ansible为用户提供的一款交互式工具,类似于Windows的cmd或者是Linux中shell

[root@centos01 ~]# ansible-console
Welcome to the ansible console.
Type help or ? to list commands.
      
root@all (2)[f:5]$ cd web    
root@web (2)[f:5]$ list                  
192.168.100.20
192.168.100.30

 四、ansible模块

1、command模块

command模块在远程主机执行基础命令,不支持管道、重定向等shell的特性

在所有主机上运行“ls ./”命令,运行前切换到/home目录下。

操作如下:

[root@centos01 ~] ansible web -m command -a "chdir=/ ls ./"
 2、shell模块

shell模块在远程主机执行命令,相当于调用远程主机的Shell进程

[root@centos01 ~] ansible web -m shell -a "echo hello world "        
192.168.100.20 | SUCCESS | rc=0 >>
hello world
 3、copy模块

copy模块用于复制指定主机文件到远程主机的指定位置

[root@centos01 ~] ansible web -m copy -a "src=/etc/hosts 
dest=/root/a1.hosts mode=777 owner=root group=root"
 4、hostname模块

hostname模块用于管理远程主机上的主机名

[root@centos01 ~] ansible 192.168.100.20 -m hostname -a "name=test"
 5、service模块

service模块为用来管理远程主机上的服务的模块

[root@centos01 ~] ansible web -m service -a "name=httpd 
enabled=yes state=restarted"
 6、user模块

user模块主要用于管理远程主机上的用户账号

[root@centos01 ~] ansible web -m user -a "name=user01 
system=yes uid=502 group=root groups=root shell=/etc/nologin 
home=/home/user01 password=pwd@123"

 

相关参考中文官网:Ansible中文权威指南- 国内专业的Ansible中文官方学习手册

https://www.cnblogs.com/-wenli/p/13292855.html

shell和ansible自动化运维实例_ansible playbook执行shell脚本_一个高效工作的家伙的博客-CSDN博客

你可能感兴趣的:(一起学ansible,ansible)