如何在 Ansible 中将新目录路径注册为变量

How to Register New Directory Path as a variable in Ansible

快速提问是否可以使用文件模块创建目录并注册新目录的路径,以便您可以将其用作变量。

我很乐意这样做,因为我正在创建一个带有时间戳的目录,但现在我很想使用该目录来存储一些数据,当我使用查找插件时,它似乎失败了,因为时间发生了变化…… .

这是我创建两个目录的前两个任务;

- name: Create Directory with timestamp to store the data if it doesn't exist
  when: inventory_hostname in groups['local']
  file:
    path: "{{store_files_path}}/{{ansible_date_time.date}}"
    state: directory
    mode: "0755"
- name: Create Directory with timestamp to store data that was run multiple times that day
  when: inventory_hostname in groups['local']
  file:
    path: "{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}"
    state: directory
    mode: "0755"

我在其他任务中使用此变量将一些数据存储在该目录中,该目录运行良好..."{{store_files_path}}/{{ansible_date_time.date}}"但现在的问题是使用查找插件失败,因为无法找到作为时间戳的第二个目录,因为查找插件实际上正在寻找具有不同时间的目录,该目录是执行任务的当前时间,与第二个时间不同任务已执行。

请帮忙,我想尝试统计功能,但我不知道如何执行这个想法。

我的查找任务

- name: Deploy to the server
  when: inventory_hostname in groups['Servers']
  authorized_key:
    user: "{{hostvars['dummy']['user']}}"
    state: present
    key: "{{ lookup('file','{{store_files_path}}/{{ansible_date_time.date}}/{{ansible_date_time.time}}/file') }}"

有几个选项:

  1. 可以保留Ansible控制机上的public键,使用lookup:

    # example: use /home/ansible/.ssh/dummy_id_rsa.pub on ansible control machine
    - authorized_key:
        user: "{{ hostvars['dummy']['user'] }}"
        key: "{{ lookup('file', '/home/ansible/.ssh/dummy_id_rsa.pub') }}"
        state: "present"
    
  2. 将 public 键作为字符串传递:

    vars:
      dummy_pub_key: "ssh-rsa AAAABC12x........... dummy@localhost"
    
    tasks:
    - authorized_key:
        user: "{{ hostvars['dummy']['user'] }}"
        key: "{{ dummy_pub_key }}"
        state: "present"
    

更新:

哦,关于将创建的路径保存到变量中的原始问题:

- name: Create Directory with timestamp to store the data if it doesn't exist
  when: inventory_hostname in groups['local']
  file:
    path: "{{store_files_path}}/{{ansible_date_time.date}}"
    state: directory
    mode: "0755"
  register: newdir_res
- name: show the newly created directory path
  debug:
    msg: "Directory path is {{ newdir_res.path }}"