ansible常用模块

1、shell模块(-m指定模块,-a为追加操作 -o为压缩输出)

  ansible all -m shell -a "echo 'mage'|passwd --stdin cui" (改密要交给shell模块,command模块很像它,但是不能改密,因为识别不了“|”管道)
  ansible all -m command -a "echo 'mage'|passwd --stdin cui"  (command模块只能识别最左边的一个shell命令)
  ansible host2 -m shell -a 'yum -y install httpd' -o  部署apache
  ansible host3 -m shell -a 'uptime' -o   查询系统负载
  ansible webserver -m shell -a 'hostname' -o -f 2   -f 2   指定线程数
  ansible webserver -m shell -a 'hostname' -o    获取主机名
  ansible-doc shell  (帮助)

2、复制模块copy,可用于远程复制脚本。

# ansible webserver -m copy -a 'src=/etc/hosts dest=/tmp/2.txt owner=root group=bin mode=777 backup=yes'  (复制带备份带指定相关属性)

# ansible all -m copy -a "content='hello\nworld' dest=/tmp/zjz.ansible mode=640"  (content='hello\nworld'  表示直接生成源文件,\n表回车)

3、脚本模块 script

script 模块在远程主机上执行 ansible 管理主机上的脚本,脚本一直存在于 ansible 管理主机本地,不需要手动拷贝到远程主机后再执行

free_form参数 :必须参数,指定需要执行的脚本,脚本位于 ansible 管理主机本地,并没有具体的一个参数名叫 free_form

chdir参数 : 此参数的作用就是指定一个远程主机中的目录,在执行对应的脚本之前,会先进入到 chdir 参数指定的目录中。

creates参数 :使用此参数指定一个远程主机中的文件,当指定的文件存在时,就不执行对应脚本。

removes参数 :使用此参数指定一个远程主机中的文件,当指定的文件不存在时,就不执行对应脚本,即存在就执行脚本。

示例

3.1、/testdir/testscript.sh 脚本将在web 主机清单中执行,执行此脚本之前,会先进入到 web 主机中的 /opt 目录

# ansible web  -m  script  -a  "chdir=/opt /testdir/testscript.sh"

3.2、creates参数

web 主机中的 /testdir/testfile1文件已经存在,ansible 主机中的 /testdir/testscript.sh 脚本将不会在 web 主机中执行。

# ansible  web -m  script -a "creates=/testdir/testfile1  /testdir/testscript.sh"

3.3、removes参数

web 主机中的 /testdir/testfile1 文件存在,ansible 主机中的 /testdir/testscript.sh 脚本则会在 web  主机中执行。

# ansible   web  -m script -a "removes=/testdir/testfile1  /testdir/testscript.sh"

4、user用户模块(ansible不支持明文传输,密码需要加密处理)

参数

user:指定要操作的用户名称
uid:指定用户的uid
comment:指定用户的注释信息
expires:指定用户的的过期时间,相当于设置/etc/shadow文件中的第8列
shell:指定用户的默认shell
home: 指定家目录
group:指定用户的基本组
groups:指定用户的附加组,新加时会覆盖原有的附加组,默认append=no
append:配合groups使用,在原有附加组的基础上追加组,append=yes
state present|absent:默认present,表示添加用户或需要用户存在;absent表示删除用户
remove:删除用户时,默认是不删除家目录,remove=no;remove=yes表示删除用户家目录
password:指定用户的密码,需要是加密后的字符串,相当于/etc/shadow文件中的第2列
update_password always|on_create:默认always
generate_ssh_key no|yes:默认为no;yes表示生成ssh密钥对,在用户家目录.ssh/目录中生成id_rsa的私钥和id_rsa.pub的公钥;若已存在同名的密钥,不会覆盖
ssh_key_file:前提是generate_ssh_key=yes,使用此参数生成ssh私钥的路径和名称,对应公钥会在同路径下生成,后缀名".pub"
ssh_key_comment:前提是generate_ssh_key=yes,使用此参数定义公钥中的注释信息,若已存在同名的密钥,不会覆盖;不指定时默认注释信息为"ansible-generated on 远程主机的主机名"
ssh_key_passphrase:前提是generate_ssh_key=yes,使用此参数设置私钥的密码,若已存在同名的密钥,不会覆盖
ssh_key_type:前提是generate_ssh_key=yes,使用此参数设置密钥对的类型,默认为rsa,若已存在同名的密钥,不会覆盖

运用

安装python-pip,并安装加密函数库-passlib
yum -y install python-pip
pip install --upgrade pip
pip install passlib

python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"
Password: 输入密码

创建用户 
ansible web  -m user -a 'name=qf  state=present password=$6$HhLLAzpF9Y1I0MVE$SeW4iE7UhN/EfGHQeBLmIIwpLI2UZpbLxLSSUeOJS66NpKWboOZ.nhPiQtvbAFkVcM.OvQleY9h4iesd3wWU2/'

创建系统用户( system=yes)
ansible web -m user -a "name=tom state=present comment='this is user tom' system=yes password=“\$6\$ay”

删除用户 
ansible webserver -m user -a 'name=qianfeng state=absent' 

修改密码 
1.生成加密密码 
echo '777777' | openssl passwd -1 -stdin ($1$XVzsJMDr$5wI4oUaQ.emxap6s.N272.) 
2.修改密码 
ansible webserver -m user -a 'name=qianfeng password="$1$XVzsJMDr$5wI4oUaQ.emxap6s.N272."' 
3.修改shell
shell ansible webserver -m user -a 'name=qianfeng shell=/sbin/nologin append=yes' 追加

5、软件包管理

ansible host2 -m yum -a 'name="httpd" state=latest' 安装apache。latest最新的
# ansible-doc yum
- state
       install (`present' or `installed', `latest')
       remove (`absent' or`removed') a package

6、服务模块

ansible host2 -m service -a 'name=httpd state=started'
ansible host2 -m service -a 'name=httpd state=started enabled=yes'
ansible host2 -m service -a 'name=httpd state=stopped'
ansible host2 -m service -a 'name=httpd state=restarted'
ansible host2 -m service -a 'name=httpd state=started enabled=no'

7、文件模块(设置文件属性)

ansible常用模块

ansible host1 -m file -a 'path=/tmp/88.txt mode=777 state=touch'
ansible host1 -m file -a 'path=/tmp/99 mode=777 state=directory'
ansible all -m file -a 'path=/tmp/fstab.ansible state=absent'
ansible all -m file -a 'path=/tmp/zjz.ansible.link src=/tmp/zjz.ansible state=link' 设置链接文件

8、setup收集模块(playbook默认运行)

  运行playbook时,默认都会运行一个名为”[Gathering Facts]”的任务,ansible通过”[Gathering Facts]”这个默认任务收集远程主机的相关信息(例如远程主机的IP地址,主机名,系统版本,硬件配置等信息),这些被收集到的远程主机信息会保存在对应的变量中,当需要使用这些信息时,可以获取对应的变量,从而使用这些信息。

返回信息很多,比如:

“ansible_all_ipv4_addresses”表示远程主机中的所有ipv4地址

“ansible_distribution”表示远程主机的系统发行版

“ansible_distribution_version”表示远程主机的系统版本号

“ansible_ens35″表示远程主机ens35网卡的相关信息

“ansible_memory_mb”表示远程主机的内存配置信息

ansible host3 -m setup
ansible host3 -m setup -a 'filter=ansible_all_ipv4_addresses'(filter过滤)

只查看某一类信息,比如过滤出主机内存配置

ansible test7 -m setup -a 'filter=ansible_memory_mb'

##使用关键字
ansible test7 -m setup -a "filter=*mb*"

ansible剧本时卡顿或卡死的优化方法

1、关闭setup默认搜集:

修改配置文件/etc/ansible/ansible.cfg
vim  /etc/ansible/ansible.cfg
gathering = explicit

#smart 表示默认收集 facts,但 facts 已有的情况下不会收集,即使用缓存 facts
#implicit 表示默认收集 facts,要禁止收集,必须使用 gather_facts: False
#explicit 则表示默认不收集,要显式收集,必须使用 gather_facts: Ture

2、调大并行线程数

fork 为 5, 并行进程数为5个,可根据服务器资源扩大

fact配置redis缓存方法

vim  /etc/ansible/ansible.cfg
[defaults]
gathering = smart
fact_caching_timeout = 86400
fact_caching = redis
#redis的ip和端口,也可使用域名
fact_caching_connection = 192.168.1.5:6379

如果redis设置了密码为admin
fact_caching_connection = 192.168.1.5:6379:0:admin 

9、cron模块

ansible all -m cron -a "minute='*/5' job='/usr/sbin/ntpdate 192.168.40.132 &>/dev/null' name='sync time'" (sync time为任务名)
ansible all -m cron -a " name='sync time' state=absent"  (取消计划任务)

10、hostname

ansible all -m hostname -a name=zjz

11、fetch 拉取模块

# ansible all -m file -a "content=zjz.tx  dest=/root"  (先创建一个共同的文件)

# ansible all -m fetch -a "src=/root/zjz.tx dest=/tmp/ flat=yes"

注:fetch不能拉取文件夹。另外加上flat=yes参数,主要是判断dest是否以 / 结尾,从而来区分这是个目录还是路径。

# ansible web -m  fetch -a "src=~/test-{{inventory_hostname}}.log   dest=~/zjz/  flat=yes"

带/ 的结果如下:  
#ls zjz/
test-ansible1.log  test-ansible2.log  test-ansible3.lo

否则生成一个叫zjz的普通文件
#ll zjz 
-rw-r--r-- 1 root root 29 Nov 22 21:36 zjz
#cat zjz 
Sun Nov 22 21:21:50 CST 2020

12、command 命令模块

它是ansible的默认模块,可以允许远程主机范围内的所有shell命令。

注意: 在command的命令中含有像`$ HOME'这样的变量和像``<“',`”>“, `“”“”,“”;“”和“”&“'将无法正常工作(如果需要这些功能,请使用[shell]模块)

13、replace模块 和 Lineinfile模块

ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,存在问题,无法正常进行替换 。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可以方便的进行替换

ansible all -m   lineinfile -a "path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing'"
ansible all -m   lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"'

剧本案例:

---
- hosts: web
  remote_user: root
  tasks:                                         
     - name: install one specific version of Apache   //tasks01.安装 
       yum:
         name: httpd
         state: installed
     - lineinfile:                               //tasks02.修改监听端口
           path: /etc/httpd/conf/httpd.conf
           regexp: '^Listen'
           line: 'Listen 8080'
     - copy:                                  //tasks03替换主页index.html
         src: /root/index.html
         dest: /var/www/html/index.html
     - service:                             //tasks04.开启服务 
         name: httpd
         enabled: yes
         state: restarted

replace模块类似于sed命令,主要也是基于正则进行匹配和替换

ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"  
ansible all -m replace -a "path=/etc/fstab regexp='^#(.*)' replace='\1'"

14、blockinfile 模块

blockinfile 会在文件中插入一段内容,插入时会根据marker 写入/更新到指定的块中,可以指定需要插入的位置
关键参数:

  1. path/dest/destfile/name :指定需要修改的文件
  2. block/content: 需要添加/修改的内容
  3. marker:标记内容,默认# BEGIN ANSIBLE MANAGED BLOCK ,例如:#{mark} test for fun , mark 会被替换为 BEGIN/END
  4. insertafter:插入指定内容之后, 默认插入到结尾
  5. insertbefore: 插入指定内容之前
注意:
如果marker 相同会更新内容,如果多次写入,注意区分marker
如果指定了marker,insertbefore/after 会不生效,仍修改该标记中的内容

例子

EXAMPLES:
# Before 2.3, option 'dest' or 'name' was used instead of 'path'
- name: insert/update "Match User" configuration block in /etc/ssh/sshd_config
  blockinfile:
    path: /etc/ssh/sshd_config
    block: |
      Match User ansible-agent
      PasswordAuthentication no

- name: insert/update eth0 configuration stanza in /etc/network/interfaces
        (it might be better to copy files into /etc/network/interfaces.d/)
  blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.2.23
          netmask 255.255.255.0

- name: insert/update configuration using a local file and validate it
  blockinfile:
    block: "{{ lookup('file', './local/ssh_config') }}"
    dest: "/etc/ssh/ssh_config"
    backup: yes
    validate: "/usr/sbin/sshd -T -f %s"

- name: insert/update HTML surrounded by custom markers after <body> line
  blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    insertafter: "<body>"
    content: |
      <h1>Welcome to {{ ansible_hostname }}</h1>
      <p>Last updated on {{ ansible_date_time.iso8601 }}</p>

- name: remove HTML as well as surrounding markers
  blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    content: ""

例子

cat block.yml
---
- hosts: 192.168.40.132
  tasks:
    - name: Add mappings to /etc/hosts
      blockinfile:
        path: /etc/hosts
        block: |
          {{ item.ip }} {{ item.name }}
        marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
      with_items:
        - { name: host1, ip: 10.10.1.10 }
        - { name: host2, ip: 10.10.1.11 }
        - { name: host3, ip: 10.10.1.12 }

运行效果

cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.40.132 root
# BEGIN ANSIBLE MANAGED BLOCK host1
10.10.1.10 host1
# END ANSIBLE MANAGED BLOCK host1
# BEGIN ANSIBLE MANAGED BLOCK host2
10.10.1.11 host2
# END ANSIBLE MANAGED BLOCK host2
# BEGIN ANSIBLE MANAGED BLOCK host3
10.10.1.12 host3
# END ANSIBLE MANAGED BLOCK host3

15、set_fact 模块(用于在play中定义task的变量)

可以通过set_fact模块在tasks中定义变量,也可以通过set_fact将一个变量的值赋予另一个变量:

先定义了一个变量testvar1,又使用register将shell模块的返回值注册到了变量shellreturn中

之后,使用set_fact模块将testvar1变量的值赋予了变量testsf1,将shellreturn变量中的stdout信息赋值给了testsf2变量,(可以将注释去掉查看变量shellreturn的值。最后,使用debug模块输出了testsf1与testsf2的值。

 cat bltest9.yml 
---
- hosts: testB
  remote_user: root
  vars:
    testvar1: test1_string
  tasks:
  - shell: "echo test2_string"
    register: shellreturn
  - set_fact:
      testsf1: "{{testvar1}}"
      testsf2: "{{shellreturn.stdout}}"
  - debug:
      msg: "{{testsf1}} {{testsf2}}"
      #var: shellreturn

另外,通过set_fact模块创建的变量还有一个特殊性,通过set_fact创建的变量就像主机上的facts信息一样,可以在之后的play中被引用。

 cat bltest10.yml 
---
- hosts: testB
  remote_user: root
  vars:
    testvar1: tv1
  tasks:
  - set_fact:
      testvar2: tv2
  - debug:
      msg: "{{testvar1}} ----- {{testvar2}}"
- hosts: testB
  remote_user: root
  tasks:
  - name: other play get testvar2
    debug:
      msg: "{{testvar2}}"
  - name: other play get testvar1
    debug:
      msg: "{{testvar1}}"

例中一共有两个play,第一个play中,我们通过两种方式创建了两个变量,第一个变量testvar1使用vas关键字创建,第二个变量使用set_fact创建。

可以发现,这两个变量在第一个play中都可以正常的输出。但是在第二个play中,testvar2可以被正常输出了,testvar1却不能被正常输出,会出现未定义testvar1的

错误,因为在第一个play中针对testB主机进行操作时,testvar1是通过vars关键字创建的,而testvar2是通过set_fact创建的,所以testvar2就好像testB的facts信息

一样,可以在第二个play中引用到,而创建testvar1变量的方式则不能达到这种效果,虽然testvar2就像facts信息一样能被之后的play引用,但是在facts信息中并不能找到testvar2,只是”效果上”与facts信息相同罢了。

16、注册变量实现跨play调用变量

前文已经总结了注册变量的用法,其实注册变量也可以在之后的play操作同一主机时被调用到

cat bltest11.yml 
---
- hosts: testB
  remote_user: root
  vars:
    testvar3: tv3
  tasks:
  - shell: "echo tv4"
    register: testvar4
  - debug:
      msg: "{{testvar3}} -- {{testvar4.stdout}}"
- hosts: testB
  remote_user: root
  tasks:
  - name: other play get testvar4
    debug:
      msg: "{{testvar4.stdout}}"
  - name: other play get testvar3
    debug:
      msg: "{{testvar3}}"

17、template模块

一个写好的配置文件,其中需要改动的配置不多,只需要在playbook中改动变量,由Jinja2模板语言处理。

ansible.builtin.template – Template a file out to a target host — Ansible Documentation

ansible之template模块 - wadeson - 博客园 (cnblogs.com) 

- name: Template a file to /etc/file.conf
  ansible.builtin.template:
    src: /mytemplates/foo.j2
    dest: /etc/file.conf
    owner: bin
    group: wheel
    mode: '0644'

- name: Template a file, using symbolic modes (equivalent to 0644)
  ansible.builtin.template:
    src: /mytemplates/foo.j2
    dest: /etc/file.conf
    owner: bin
    group: wheel
    mode: u=rw,g=r,o=r

- name: Copy a version of named.conf that is dependent on the OS. setype obtained by doing ls -Z /etc/named.conf on original file
  ansible.builtin.template:
    src: named.conf_{{ ansible_os_family }}.j2
    dest: /etc/named.conf
    group: named
    setype: named_conf_t
    mode: 0640

- name: Create a DOS-style text file from a template
  ansible.builtin.template:
    src: config.ini.j2
    dest: /share/windows/config.ini
    newline_sequence: '\r\n'

- name: Copy a new sudoers file into place, after passing validation with visudo
  ansible.builtin.template:
    src: /mine/sudoers
    dest: /etc/sudoers
    validate: /usr/sbin/visudo -cf %s

- name: Update sshd configuration safely, avoid locking yourself out
  ansible.builtin.template:
    src: etc/ssh/sshd_config.j2
    dest: /etc/ssh/sshd_config
    owner: root
    group: root
    mode: '0600'
    validate: /usr/sbin/sshd -t -f %s
    backup: yes

18、get_url 模块:用于将文件或软件从http、https或ftp下载到本地节点上或被管理机节点上

# 1、下载文件到指定目录:
ansible all -m get_url -a "url=http://www.guojinbao.com dest=/tmp/guojinbao mode=0440 force=yes"
需要添加登录名密码的网站,使用url_password、url_username参数来定义

# 2、解压ansible管理机上的压缩文件到远程主机:
ansible all -m unarchive -a "src=/tmp/install/zabbix-3.0.4.tar.gz dest=/tmp/ mode=0755 copy=yes"

# 3、解压远程主机上的文件到目录:
ansible all -m unarchive -a "src=/tmp/install/zabbix-3.0.4.tar.gz dest=/tmp/ mode=0755 copy=no"

ansible常用模块

 

 

 

 

 

https://www.cnblogs.com/fanlong0212/p/12185290.html        ansible 离线包制作和离线部署  

相关文章:

  • 2021-11-20
  • 2021-10-17
猜你喜欢
  • 2022-12-23
  • 2021-10-18
  • 2019-12-18
  • 2021-09-08
相关资源
相似解决方案