ansible常用模块使用详解

Ansible中常用模块 Ansible中常用模块实验环境配置ansible实现管理的方式及执行方式中如何获得帮助2.ansible命令运行方式及常用参数3.ansible的基本颜色代表信4.ansible中的常用模块五级标题六级标题 实验环境配置 建立免密登录 编写shell脚本修改受控机权限 建立免密登录连接 ansible实现管理的方式及执行方式中如何获得帮助 Ad-Hoc ##利用ansible命令直接完成管理,主要用于临时命令使用场景 playbook ##ansible脚本,主要用于大型项目场景,需要前期的规划 阅读详情
  • ping (查看远程机器是否畅通)

命令行版本:

[root@ansible-leader /etc/ansible/play]$ansible web -m  ping
[WARNING]: Found both group and host with same name: leader
web2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}
web1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

playbook版本:

#编辑playbook文件
[root@ansible-leader /etc/ansible/play]$vim ping_web_servers.yml
---
- name: Test connectivity to web servers
  hosts: web
  tasks:
    - name: Ping the web server to check connectivity
      ansible.builtin.ping:

#执行playbook文件
[root@ansible-leader /etc/ansible/play]$ansible-playbook ping_web_servers.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Test connectivity to web servers] ************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [web2]
ok: [web1]

TASK [Ping the web server to check connectivity] ***************************************************************************************************************************
ok: [web1]
ok: [web2]

PLAY RECAP *****************************************************************************************************************************************************************
web1                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
  • yum (远程下载远程机器上的服务)

命令行版本:

#安装vsftpd服务
[root@ansible-leader /etc/ansible/play]$ansible web -m yum -a "name=vsftpd state=present"
[WARNING]: Found both group and host with same name: leader
web2 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "msg": "",
    "rc": 0,
    "results": [
        "vsftpd-3.0.2-29.el7_9.x86_64 providing vsftpd is already installed"
    ]
}
web1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "msg": "",
    "rc": 0,
    "results": [
        "vsftpd-3.0.2-29.el7_9.x86_64 providing vsftpd is already installed"
    ]
}

#卸载vsftpd服务
[root@ansible-leader /etc/ansible/play]$ansible web -m yum -a "name=vsftpd state=removed"
[WARNING]: Found both group and host with same name: leader
web1 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "removed": [
            "vsftpd"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:3.0.2-29.el7_9 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package        Arch           Version             Repository        Size\n================================================================================\nRemoving:\n vsftpd         x86_64         3.0.2-29.el7_9            @updates         353 k\n\nTransaction Summary\n================================================================================\nRemove  1 Package\n\nInstalled size: 353 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Erasing    : vsftpd-3.0.2-29.el7_9.x86_64                                 1/1 \n  Verifying  : vsftpd-3.0.2-29.el7_9.x86_64                                 1/1 \n\nRemoved:\n  vsftpd.x86_64 0:3.0.2-29.el7_9                                                \n\nComplete!\n"
    ]
}
web2 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "changes": {
        "removed": [
            "vsftpd"
        ]
    },
    "msg": "",
    "rc": 0,
    "results": [
        "Loaded plugins: fastestmirror\nResolving Dependencies\n--> Running transaction check\n---> Package vsftpd.x86_64 0:3.0.2-29.el7_9 will be erased\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package        Arch           Version             Repository        Size\n================================================================================\nRemoving:\n vsftpd         x86_64         3.0.2-29.el7_9            @updates         353 k\n\nTransaction Summary\n================================================================================\nRemove  1 Package\n\nInstalled size: 353 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Erasing    : vsftpd-3.0.2-29.el7_9.x86_64                                 1/1 \n  Verifying  : vsftpd-3.0.2-29.el7_9.x86_64                                 1/1 \n\nRemoved:\n  vsftpd.x86_64 0:3.0.2-29.el7_9                                                \n\nComplete!\n"
    ]
}

playbook版本:

#安装vsftpd服务playbook文件:


[root@ansible-leader /etc/ansible/play]$cat install_vsftpd.yml
---
- name: Install the latest version of Vsftpd on webservers
  hosts: web
  tasks:
    - name: Ensure Vsftpd is at the latest version
      yum:
        name: vsftpd
        state: present

#安装vsftpd服务 



[root@ansible-leader /etc/ansible/play]$ansible-playbook install_vsftpd.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Install the latest version of Vsftpd on webservers] ******************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [web1]
ok: [web2]

TASK [Ensure Vsftpd is at the latest version] ******************************************************************************************************************************
changed: [web1]
changed: [web2]

PLAY RECAP *****************************************************************************************************************************************************************
web1                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

#卸载vsftpd服务

#卸载vsftpd服务playbook文件 


[root@ansible-leader /etc/ansible/play]$cat removed_vsftpd.yml
---
- name: Removed the Vsftpd on webservers
  hosts: web
  tasks:
    - name: Ensure Vsftpd is at the latest version
      yum:
        name: vsftpd
        state: removed

#卸载vsftpd服务playbook执行: 


[root@ansible-leader /etc/ansible/play]$ansible-playbook removed_vsftpd.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Install the latest version of Vsftpd on webservers] ******************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [web2]
ok: [web1]

TASK [Ensure Vsftpd is at the latest version] ******************************************************************************************************************************
changed: [web1]
changed: [web2]

PLAY RECAP *****************************************************************************************************************************************************************
web1                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

 

  • template

原版nginx配置文件

[root@ansible-leader /etc/ansible/play]$cat /etc/nginx/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

配置一个jinja2的配置文件模板

[root@ansible-leader /path/to]$vim nginx.conf.j2
user {{ nginx_user }};
worker_processes {{ ansible_processor_cores }};
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}



#这里在文件中指定了两个变量,
nginx_user :    这个变量会砸ansible的playbook中进行定义.
qnsible_processor_cores :     这个变量是ansible可以自动使用setpu查询出来的系统环境变量

 书写playbook文件

[root@ansible-leader /etc/ansible/play]$vim deploy_nginx_conf.yml
---
- name: Deploy Nginx configuration using template
  hosts: web
  vars:
    nginx_user: www
  tasks:
    - name: Copy Nginx config from template
      template:
        src: /path/to/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: '0644'
      notify:
        - restart nginx

  handlers:
    - name: restart nginx
      service:
        name: nginx
        state: restarted


#vars    字段定义的就是nginx配置文件中预先定义好的变量名称,会在template的过程中自动进行原文替换.
#src      是原文件
#dest     是目标文件
#owner    指定属主
#grout    指定属组
#mode     指定权限
#notify   上述操作完成后执行handlers做操作,这里指定的handler名称是restart nginx,
#handler  指定操作过程使用service模块
#name     对nginx服务操作,
#state     重启

执行操作 


[root@ansible-leader /etc/ansible/play]$ansible-playbook deploy_nginx_conf.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Deploy Nginx configuration using template] ***************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Copy Nginx config from template] *************************************************************************************************************************************
ok: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

查看执行结果

[root@ansible-leader /etc/ansible/play]$cat /etc/nginx/nginx.conf
user www;
worker_processes 1;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
  • copy

命令行版本

[root@ansible-leader /path/to]$ansible leader -m copy -a "src=/path/to/nginx.conf.j2 dest=/tmp/nginx.conf.j2 owner=www group=www mode='0644'"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "checksum": "efbcf07e7e75f8f162cc01489b08b88b1e10f03a",
    "dest": "/tmp/nginx.conf.j2",
    "gid": 1001,
    "group": "www",
    "mode": "0644",
    "owner": "www",
    "path": "/tmp/nginx.conf.j2",
    "secontext": "unconfined_u:object_r:admin_home_t:s0",
    "size": 659,
    "state": "file",
    "uid": 1001
}

#这里如果执行的远程服务器或者本地执行服务器没有对应用户的话那么执行会报错.

 playbook

[root@ansible-leader /etc/ansible/play]$vim copy_file.yaml
---
- name: Copy a file to remote hosts
  hosts: leader
  tasks:
    - name: Copy example configuration file
      copy:
        src: /path/to/nginx.conf.j2
        dest: /tmp/nginx.conf.bak
        owner: root
        group: root
        mode: '0644'
playbook执行结果
[root@ansible-leader /etc/ansible/play]$ansible-playbook copy_file.yaml
[WARNING]: Found both group and host with same name: leader

PLAY [Copy a file to remote hosts] *****************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Copy example configuration file] *************************************************************************************************************************************
changed: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

[root@ansible-leader /etc/ansible/play]$ll /tmp/
total 16
-rw-r--r--. 1 root root 659 Apr  1 13:48 nginx.conf.bak
-rw-r--r--. 1 www  www  659 Apr  1 13:42 nginx.conf.j2

 

  • user (远程创建远程机器的用户)

命令行版本
[root@ansible-leader /etc/ansible/play]$ansible leader -m user -a "name=newuser shell=/bin/bash uid=1003 group=users"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 100,
    "home": "/home/newuser",
    "name": "newuser",
    "shell": "/bin/bash",
    "state": "present",
    "system": false,
    "uid": 1003
}

playbook版本:

playbook文件:

 

#增加一个用户
[root@ansible-leader /etc/ansible/play]$vim useradd.yml
---
- name: Create a new user on remote hosts
  hosts: leader
  tasks:
    - name: Ensure user newuser is present
      user:
        name: newuser2
        comment: "New User"
        uid: 1004
        group: users
        shell: /bin/bash
        state: present

执行playbook文件
[root@ansible-leader /etc/ansible/play]$ansible-playbook useradd.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Create a new user on remote hosts] ***********************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Ensure user newuser is present] **************************************************************************************************************************************
changed: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
查看用户添加状况
[root@ansible-leader /etc/ansible/play]$cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
.
.
.

newuser2:x:1004:100:New User:/home/newuser2:/bin/bash
删除一个用户的playbook:
[root@ansible-leader /etc/ansible/play]$vim userremoved.yml
---
- name: Delete a old user on remote hosts
  hosts: leader
  tasks:
    - name: Ensure user newuser is absent
      user:
        name: newuser2
        uid: 1004
        group: users
        shell: /bin/bash
        state: absent
 执行playbook
[root@ansible-leader /etc/ansible/play]$ansible-playbook userremoved.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Create a new user on remote hosts] ***********************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Ensure user newuser is present] **************************************************************************************************************************************
changed: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
 查看结果:
[root@ansible-leader /etc/ansible/play]$cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
.
.
.
.
newuser:x:1003:100::/home/newuser:/bin/bash

#newuser2已经被删除
  • group (远程创建远程机器的用户组)

命令行版本:

添加用户组:
[root@ansible-leader /etc/ansible/play]$ansible leader -m group -a "name=newgroup state=present"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "gid": 1002,
    "name": "newgroup",
    "state": "present",
    "system": false
}

#查看结果
[root@ansible-leader /etc/ansible/play]$getent group|grep newgroup
newgroup:x:1002:

删除用户组:
[root@ansible-leader /etc/ansible/play]$ansible leader -m group -a "name=newgroup state=absent"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "newgroup",
    "state": "absent"
}
#查看结果
[root@ansible-leader /etc/ansible/play]$getent group|grep newgroup

 playbook版本添加用户组:

#playbook
[root@ansible-leader /etc/ansible/play]$vim group_add.yml
---
- name: Add a new group on remote hosts
  hosts: all
  tasks:
    - name: Ensure group newgroup is present
      group:
        name: newgroup
        state: present
#执行结果
[root@ansible-leader /etc/ansible/play]$ansible-playbook group_add.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Add a new group on remote hosts] *************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [web1]
ok: [web2]
ok: [leader]

TASK [Ensure group newgroup is present] ************************************************************************************************************************************
changed: [web1]
changed: [leader]
changed: [web2]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web1                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

#查看结果
[root@ansible-leader /etc/ansible/play]$getent group|grep new
newgroup:x:1002:
 删除group用户组playbook文件:
[root@ansible-leader /etc/ansible/play]$vim group_remove.yml
---
- name: Remove a group from remote hosts
  hosts: all
  tasks:
    - name: Ensure group oldgroup is absent
      group:
        name: newgroup
        state: absent
执行结果:
[root@ansible-leader /etc/ansible/play]$ansible-playbook group_remove.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Remove a group from remote hosts] ************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]
ok: [web2]
ok: [web1]

TASK [Ensure group oldgroup is absent] *************************************************************************************************************************************
changed: [web2]
changed: [web1]
changed: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web1                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

[root@ansible-leader /etc/ansible/play]$getent group|grep new

 

  • service (远程执行远程机器上的服务启停操作)

命令行版本

启动nginx服务
[root@ansible-leader /etc/ansible/play]$ansible leader -m service -a "name=nginx state=started enabled=yes"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "enabled": true,
    "name": "nginx",
    "state": "started",
    "status": {
.
.
.
.
        "WatchdogTimestamp": "Tue 2025-04-01 12:11:10 CST",
        "WatchdogTimestampMonotonic": "86620163804",
        "WatchdogUSec": "0"
    }
}

#指定service模块
#name:    nginx服务进行操作
#state:    started启动操作
#enable:    yes加入开机自启动
命令行停止nginx服务:
[root@ansible-leader /etc/ansible/play]$ansible leader -m service -a "name=nginx state=stopped"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": true,
    "name": "nginx",
    "state": "stopped",
    "status": {
        "ActiveEnterTimestamp": "Tue 2025-04-01 12:11:10 CST",
        "ActiveEnterTimestampMonotonic": "86620163828",
.
.
.
.
        "Wants": "network-online.target",
        "WatchdogTimestamp": "Tue 2025-04-01 12:11:10 CST",
        "WatchdogTimestampMonotonic": "86620163804",
        "WatchdogUSec": "0"
    }
}
playbook版本启动服务:

 

#playbook启动文件
[root@ansible-leader /etc/ansible/play]$vim start_service.yml
---
- name: Start a service on remote hosts
  hosts: leader
  tasks:
    - name: Ensure nginx service is started
      service:
        name: nginx
        state: started
        enabled: yes


#执行playbook
[root@ansible-leader /etc/ansible/play]$ansible-playbook start_service.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Start a service on remote hosts] *************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Ensure nginx service is started] *************************************************************************************************************************************
changed: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

#检查服务状态
[root@ansible-leader /etc/ansible/play]$systemctl status nginx
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2025-04-01 15:01:16 CST; 4min 2s ago
     Docs: http://nginx.org/en/docs/
  Process: 18098 ExecStop=/bin/sh -c /bin/kill -s TERM $(/bin/cat /var/run/nginx.pid) (code=exited, status=0/SUCCESS)
  Process: 18317 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 18318 (nginx)
    Tasks: 2
   Memory: 2.3M
   CGroup: /system.slice/nginx.service
           ├─18318 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
           └─18319 nginx: worker process

Apr 01 15:01:16 ansible-leader systemd[1]: Starting nginx - high performance web server...
Apr 01 15:01:16 ansible-leader systemd[1]: Started nginx - high performance web server.
[root@ansible-leader /etc/ansible/play]$
playbook版本停止服务:
#playbook文件
[root@ansible-leader /etc/ansible/play]$vim stop_service.yml
---
- name: Stop a service on remote hosts
  hosts: leader
  tasks:
    - name: Ensure nginx service is stopped
      service:
        name: nginx
        state: stopped

#执行playbook操作
[root@ansible-leader /etc/ansible/play]$ansible-playbook stop_service.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Stop a service on remote hosts] **************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Ensure nginx service is stopped] *************************************************************************************************************************************
changed: [leader]

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

#检查服务状态
[root@ansible-leader /etc/ansible/play]$systemctl status nginx
● nginx.service - nginx - high performance web server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Tue 2025-04-01 15:06:25 CST; 7s ago
     Docs: http://nginx.org/en/docs/
  Process: 18525 ExecStop=/bin/sh -c /bin/kill -s TERM $(/bin/cat /var/run/nginx.pid) (code=exited, status=0/SUCCESS)
  Process: 18317 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
 Main PID: 18318 (code=exited, status=0/SUCCESS)

Apr 01 15:01:16 ansible-leader systemd[1]: Starting nginx - high performance web server...
Apr 01 15:01:16 ansible-leader systemd[1]: Started nginx - high performance web server.
Apr 01 15:06:25 ansible-leader systemd[1]: Stopping nginx - high performance web server...
Apr 01 15:06:25 ansible-leader systemd[1]: Stopped nginx - high performance web server.
 
  • shell (远程执行远程机器上的的命令)

命令行版本
#远程主机执行命令行shell操作
[root@ansible-leader /etc/ansible/play]$ansible leader -m shell -a "ls /var/log >> /tmp/loglist.txt"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED | rc=0 >>

#检查操作结果
[root@ansible-leader /etc/ansible/play]$cat /tmp/loglist.txt
anaconda
spooler
spooler-20250331
tallylog
tuned
wtmp
yum.log

playbook版本:

playbook文件
[root@ansible-leader /etc/ansible/play]$vim run_shellcommand.yml
---
- name: Run a shell command on remote hosts
  hosts: leader
  tasks:
    - name: List contents of /var/log and append to file
      shell: ls /var/log >> /tmp/loglist.txt
      register: shell_output

    - name: Show the result of the shell command
      debug:
        msg: "{{shell_output.stdout}}"
 执行playbook
[root@ansible-leader /etc/ansible/play]$ansible-playbook run_shellcommand.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Run a shell command on remote hosts] *********************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [List contents of /var/log and append to file] ************************************************************************************************************************
changed: [leader]

TASK [Show the result of the shell command] ********************************************************************************************************************************
ok: [leader] => {
    "msg": ""
}

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

#检查结果
[root@ansible-leader /etc/ansible/play]$cat /tmp/loglist.txt
anaconda
audit
boot.log
.
.
.
yum.log

  • script (远程执行控制机器的本地脚本)

  • script 模块允许你在远程主机上运行本地脚本。Ansible 会将指定的脚本传输到远程主机,然后在远程主机上执行它。这非常适合需要在多个远程主机上运行相同脚本的情况。

控制机器上创建一个脚本用于后面远程执行使用

[root@ansible-leader /etc/ansible/scripts]$vim check_tmp.sh
#!/bin/bash
ls -l /tmp/
命令行版本
[root@ansible-leader /etc/ansible/scripts]$ansible leader -m script -a "/etc/ansible/scripts/check_tmp.sh"
[WARNING]: Found both group and host with same name: leader
leader | CHANGED => {
    "changed": true,
    "rc": 0,
    "stderr": "Shared connection to leader closed.\r\n",
    "stderr_lines": [
        "Shared connection to leader closed."
    ],
    "stdout": "/root/.bashrc: line 17: bind: warning: line editing not enabled\r\n/root/.bashrc: line 18: bind: warning: line editing not enabled\r\ntotal 20\r\n-rw-r--r--. 1 root root 558 Apr  1 15:13 loglist.txt\r\n-rw-r--r--. 1 root root 659 Apr  1 13:48 nginx.conf.bak\r\n-rw-r--r--. 1 www  www  659 Apr  1 13:42 nginx.conf.j2\r\n-rw-r--r--. 1 root root  15 Mar 31 14:20 test\r\n-rw-------. 1 root root  15 Mar 31 18:24 test1\r\n",
    "stdout_lines": [
        "/root/.bashrc: line 17: bind: warning: line editing not enabled",
        "/root/.bashrc: line 18: bind: warning: line editing not enabled",
        "total 20",
        "-rw-r--r--. 1 root root 558 Apr  1 15:13 loglist.txt",
        "-rw-r--r--. 1 root root 659 Apr  1 13:48 nginx.conf.bak",
        "-rw-r--r--. 1 www  www  659 Apr  1 13:42 nginx.conf.j2",
        "-rw-r--r--. 1 root root  15 Mar 31 14:20 test",
        "-rw-------. 1 root root  15 Mar 31 18:24 test1"
    ]
}

playbook版本:

playbook文件
[root@ansible-leader /etc/ansible/play]$vim run_local_script.yml
---
- name: Run a local script on remote hosts
  hosts: leader
  tasks:
    - name: Execute myscript.sh on the remote host
      script: /etc/ansible/scripts/check_tmp.sh
      args:
        executable: /bin/bash # 如果脚本需要特定解释器,请指定
      register: script_result

    - name: Show the result of the script execution
      debug:
        msg: "{{ script_result.stdout }}"

#script:    脚本所在位置,
#args:      这里知道了一个脚本执行的解释器,这里使用的是bash,
如果是py那就指定py,如果是golang 那就指定go.的解释器路径.
执行playbook
[root@ansible-leader /etc/ansible/play]$ansible-playbook run_local_script.yml
[WARNING]: Found both group and host with same name: leader

PLAY [Run a local script on remote hosts] **********************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [leader]

TASK [Execute myscript.sh on the remote host] ******************************************************************************************************************************
changed: [leader]

TASK [Show the result of the script execution] *****************************************************************************************************************************
ok: [leader] => {
    "msg": "/root/.bashrc: line 17: bind: warning: line editing not enabled\r\n/root/.bashrc: line 18: bind: warning: line editing not enabled\r\ntotal 20\r\n-rw-r--r--. 1root root 558 Apr  1 15:13 loglist.txt\r\n-rw-r--r--. 1 root root 659 Apr  1 13:48 nginx.conf.bak\r\n-rw-r--r--. 1 www  www  659 Apr  1 13:42 nginx.conf.j2\r\n-rw-r--r--. 1 root root  15 Mar 31 14:20 test\r\n-rw-------. 1 root root  15 Mar 31 18:24 test1\r\n"
}

PLAY RECAP *****************************************************************************************************************************************************************
leader                     : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

三、ansible常用模块 ansible常用模块查看当前支持的模块ansibke-doc -s 模块名查看该模块的参数。 阅读详情

相关推荐

运维神器Ansible的常用模块

话不多说,今天分享一下Ansible的常用模块,建议收藏

yz2322944912的博客 2176

5.2--->Ansible中常用的模块

目录 一.ansible实现管理的方式 二. Ad-Hoc执行方式中如何获得帮助 三.ansible命令运行方式及常用参数 四.ansible的基本颜色代表 五.ansible中的常用模块 1.command 2.shell 3.script 4. copy 5.fetch 6.file 7.archive 8.unarchive 9.hostname 10.cron 11.yum_repository 12.dnf 13.service 14.firewalld

m0_59744025的博客 1229

Ansible常用模块及使用示例

Ansible使用模块化的方式工作,每个模块都有特定的功能,用户可以通过编写Playbook(剧本)来组合这些模块实现复杂的自动化任务。

m_2076的博客 1632

ansible的常见模块

ansible常见的模块:yum、file、Shell、ping、group、user、copy、command、raw、template、Service、script

a221777的博客 990

《Ansible模块篇:Ansible常用模块介绍及实战》

系列文章目录 提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加 例如:第一章 Python 机器学习入门之pandas的使用 提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录系列文章目录前言一、pandas是什么?二、使用步骤1.引入库2.读入数据总结 前言 提示:这里可以添加本文要记录的大概内容: 例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。 提示:以下是本篇文章正文内容,下面案例

东城绝神 3907

Linux Ansible 常用模块教程详解

Ansible 是一款流行的开源自动化工具,它通过简单的模型来管理配置服务器、部署软件以及执行各种IT任务。Ansible 使用无代理(agentless)架构,这意味着不需要在被管理的节点上安装额外的软件。

广阔天地,大有作为 1273

Ansible常用模块

bash无论在命令行上执行,还是bash脚本中,都需要调用cd、ls、copy、yum等命令;模块就是Ansible的“命令”,模块是ansible命令行和脚本中都需要调用的。常用的Ansible模块有yum、copy、template等。

weixin_53388991的博客 6432

Ansible中常用的模块

ansible实现管理的方式、命令运行方式、基本颜色代表和常用模块 1.command模块;2.shell模块;3.script模块;4.copy模块5.fetch模块;6.file模块;7.unarchive模块;8.archive模块;9.hostname模块;10.cron模块;11.yum_repository模块;12.dnf模块;13.service模块;14.firewall15.user模块 16.group模块;17.lineinfile模块、replac、setup模块、 debug模块

LRJ2034203479的博客 7381

Ansible常用模块介绍

ansible 默认提供了很多模块来供我们使用。在 Linux 中,我们可以通过 ansible-doc -l 命令查看到当前 ansible 都支持哪些模块,通过 ansible-doc -s 模块名 又可以查看该模块有哪些参数可以使用。 官网文档:http://docs.ansible.com/ansible/latest/list_of_all_modules.htmlAnsible常

pushiqiang的博客 3万+

【ISP图像处理】Demosaic去马赛克技术演进与边缘优化策略

本文深入解析了ISP图像处理中的Demosaic(去马赛克)技术。从Bayer阵列原理出发,梳理了从双线性插值、Hamilton-Adams边缘导向算法到利用通道相关性与自相似性的技术演进历程,并重点探讨了针对边缘与纹理伪影的优化策略,为工程实践中的算法选型与硬件协同设计提供了专业指导。

weixin_29091445的博客 387

【转载】参数估计(Parameter Estimation):频率学派(最大似然估计MLE、最大后验估计MAP)与贝叶斯学派(贝叶斯估计BPE)

基础 频率学派与贝叶斯学派 http://www.douban.com/group/topic/16719644/ http://www.zhihu.com/question/20587681 最大似然估计(Maximum likelihood estimation,MLE) http://baike.baidu.com/view/1918804.htm http://baike.baidu.co

影 的专栏 3413

【ansible】ansible模块的使用

ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,存在问题,无法正常进行替换。参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除。功能:yum 管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本apt 模块管理 Debian 相关版本的软件包。功能:检查文件或文件系统的状态。

Mo_nor的博客 1505

how2heap 深入学习(1)

how2heap glibc 2.23学习

CoLin的pwn小屋 3179

2、Ansible常用模块

bash无论在命令行上执行,还是bash脚本中,都需要调用cd、ls、copy、yum等命令;模块就是Ansible的“命令”,模块是ansible命令行和脚本中都需要调用的。常用的Ansible模块有yum、copy、template等。2. Ansible。

lingqianhui的博客 805

东方马达步进电机AZM66AK-HS100+AZD-KD调试经验记录

东方马达步进电机AZM66AK-HS100+AZD-KD调试经验记录(20170803YC) 本次总结主要实现的功能如下:用MEXE02软件在步进电机驱动器中设置好控制动作,每个控制动作有一个特定的编号。之后通过PC和驱动器之间的485通讯,发送相关指令,使步进电机按照一定编号的控制动作运转。 参考资料:东方马达步进电机AZM66AK-HS100+AZD-KD的产品手册,可在官网下载。 A....

dahailuoa6的博客 1万+

YOLOv11【第六章:模型压缩与极致优化篇·第4节】Lamp 剪枝算法:无需超参的自动化剪枝策略!

🏆 本文收录于专栏 《YOLOv11实战:从入门到深度优化》。本专栏围绕 YOLOv11 的改进、训练、部署与工程优化 展开,系统梳理并复现当前主流的 YOLOv11 实战案例与优化方案,内容目前已覆盖 分类、检测、分割、追踪、关键点、OBB 检测 等多个方向。

**My Coding Family** 1210

ansible 常用模块

调用后返回很多对应主机的信息,在后面的操作中可以根据不同的信息来做不同的操作。它不会通过shell进行处理,比如$HOME和操作如"<",">","|",";#特殊的时间范围,参数:reboot(重启时),annually(每年),monthly(每月),weekly(每周),daily(每天),hourly(每小时)我们的setup模块还有一个很好用的功能就是可以保存我们所筛选的信息至我们的主机上,同时,文件名为我们被管制的主机的IP,这样方便我们知道是哪台机器出的问题。#在重启服务的过程中,是否等待。

zbw0323的博客 2216

【R语言】基于Biomod2集成平台探究物种分布区的构建流程(SDMs)

我为什么想要写这个内容呢?其实我已经想了很久了,但是一直没有把所有的代码给理清楚,此外这将是我之后研究的主要方向。本博客讲述了如何基于Biomod2集成平台构建物种分布模型的全流程,以及我在使用该模型时的一些心得,同时还有我提供的一些小福利(一键处理代码),可以十分快捷的帮助你完成SDMs的构建,写出你的中英文论文。

amyniez的博客,欢迎交流讨论 3889

ansible的常用模块及模块的使用

自动化运维工具--ansible常用的12个模块及使用

该学习了a的博客 1516

地平线旭日X3开发板--使用Opencv显示CSI摄像头例程

但是从libsrcampy获取的摄像头图像格式是NV12,无法直接在opencv上显示或者处理,调试过程发现旭日派无法直接用opencv的VideoCapture()调用CSI摄像头,需要使用opencv来做开发的小伙伴可以做个参考,效果如下图所示。需要使用libsrcampy库来获取CSI摄像头图像,为了能够使用opencv的API来处理图像,需要增加NV12转化成bgr像素格式的函数。opencv显示图像.png。

bingdund的博客 541

C/C++跳动的爱心(完整代码)

C语言实现跳动的爱心的完整代码。

AIGC 5842

Ansible常用模块详解

Ansible常用模块详解命令模块commandshell文件模块copyfile安装模块yum服务模块service挂载模块mount定时任务cron用户模块groupuser压缩解压unarchive 命令模块 command 概要 命令模块 适合使用简单的命令 无法支持&amp;amp;amp;amp;amp;amp;amp;amp;amp;quot;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;&amp;amp;amp;amp;amp

一个小运维 3万+

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

ansible 常用模块1

总结一点,在我们复制目录时,权限的指定只有文件生效,目录不生效,属组和属主的指定,若目标节点存在,则不生效,若不存在则生效。ansible之所以功能强大,不是ansible本身,是因为它有众多的模块,前文我们介绍了ansible的基础介绍,系列命令的用法以及选项的说明,通过前文的学习我们知道了ansible是基于python语言编写,我们在执行一条ansible命令通常会指定一个模块,即便不指定它也有默认的模块,它的工作流程就是通过各种模块去完成对远程主机的管理、配置等操作。下面来看看shell模块。

smucff的博客 1669

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

Ansible 常用模块

Ansible 默认提供了很多模块来供我们使用。 我们可以通过 ansible-doc -l 命令查看到当前 ansible 都支持哪些模块通过 ansible-doc -s 模块名 可以查看该模块有哪些参数可以使用。

Toasten 1367

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

ansible常用模块

9 state: directory:如果目录不存在,创建目录 file:即使文件不存在,也不会被创建 link:创建软链接 hard:创建硬链接 touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间 absent:删除目录、文件或者取消链接文件。如果路径是一个目录,它将递归复制。5 force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。

happy_king_zi的博客 1255
上一篇: k8s中RBAC使用
下一篇: 编译安装nginx
被一米六支配的恐惧
博客等级 码龄9年 246粉丝 95原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值