如何通过 Ansible 自动化创建名为 “example” 的目录?

ansible.builtin.file 管理文件及其属性 今天我们要讨论的是 Ansible 的 file 模块。 模块的完整名称是 ansible.builtin.file,这意味着它是 Ansible 自带的模块集合的一部分,并且与 Ansible 一起分发。 这是一个非常稳定的模块,已经存在多年。 它可以在多种操作系统中运行。 它用于管理文件及其属性。 对于 Windows 目标,建议使用 ansible.windows.win_file 模块。

参数:

  • path(字符串,别名:dest、name):文件路径
  • state(字符串):file、absent、directory、hard、link、touch
  • mode/owner/group:权限
  • setype/seuser/selevel:SELinux 属性

该模块有一些参数用于执行各种任务。 唯一必需的参数是 path,它指定了你要操作的文件或目录的文件系统路径。 state 参数定义了我们要修改的对象类型,默认值为 file,但在我们的用例中,我们需要使用 directory 选项。

示例: 如何使用 Ansible 的 file 模块在 Linux 中为用户 devops 的家目录中创建一个名为 “example” 的目录。

代码: create_directory.yml 文件内容如下:

1 ---
2 - name: file 模块示例
3   hosts: all
4   vars:
5     mydir: "~/example"
6   tasks:
7     - name: 创建目录
8       ansible.builtin.file:
9         path: "{{ mydir }}"
10        state: directory
11        owner: devops
12        group: users
13        mode: '0644'

执行命令:

1 $ ansible-playbook -i demo/inventory create\ directory/file.yml
2 PLAY [file 模块示例] ******************************************
3 TASK [Gathering Facts] ***************************************
4 ok: [demo.example.com]
5 TASK [创建目录] **********************************************
6 changed: [demo.example.com]
7 PLAY RECAP ****************************************************
8 demo.example.com           : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

执行前:

1 $ ssh devops@demo.example.com
2 [devops@demo ~]$ ls -al
3 total 16
4 drwx------. 4 devops wheel  111 Nov 14 13:43 .
5 drwxr-xr-x. 5 root   root    50 Nov  8 17:07 ..
6 drwx------. 3 devops wheel   17 Sep  6 05:53 .ansible
7 -rw-------. 1 devops wheel 2849 Nov 14 13:43 .bash_history
8 -rw-r--r--. 1 devops wheel   18 Dec  4  2020 .bash_logout
9 -rw-r--r--. 1 devops wheel  141 Dec  4  2020 .bash_profile
10 -rw-r--r--. 1 devops wheel  376 Dec  4  2020 .bashrc
11 drwx------. 2 devops wheel   94 Sep 16 10:09 .ssh
12 [devops@demo ~]$

执行后:

1 $ ssh devops@demo.example.com
2 [devops@demo ~]$ ls -al
3 total 16
4 drwx------. 5 devops wheel  126 Nov 14 13:45 .
5 drwxr-xr-x. 5 root   root    50 Nov  8 17:07 ..
6 drwx------. 3 devops wheel   17 Sep  6 05:53 .ansible
7 -rw-------. 1 devops wheel 2861 Nov 14 13:44 .bash_history
8 -rw-r--r--. 1 devops wheel   18 Dec  4  2020 .bash_logout
9 -rw-r--r--. 1 devops wheel  141 Dec  4  2020 .bash_profile
10 -rw-r--r--. 1 devops wheel  376 Dec  4  2020 .bashrc
11 drwx------. 2 devops wheel   94 Sep 16 10:09 .ssh
12 drw-r--r--. 2 devops users    6 Nov 14 13:45 example