用户从命令行参数写入文件 - Ansible

时间:2017-11-06 09:33:58

标签: ansible

我正在尝试使用lineinfile在文件中写一行。

文件的名称将在运行时由用户作为命令行参数传递给playbook。

这是任务的样子:

  # Check for timezone.
    - name: check timezone
      tags: timezoneCheck
      register: timezoneCheckOut
      shell: timedatectl | grep -i "Time Zone" | awk --field-separator=":" '{print $2}' | awk --field-separator=" " '{print $1}'
    - lineinfile:
        path: {{ output }}
        line: "Did not find { DesiredTimeZone }"
        create: True
        state: present
        insertafter: EOF
      when: timezoneCheckOut.stdout != DesiredTimezone
    - debug: var=timezoneCheckOut.stdout

我的问题是:
1.如何将命令行参数指定为要写入的目标文件(path)?
2.如何将参数DesiredTimeZone(在外部变量文件中指定)附加到line参数?

2 个答案:

答案 0 :(得分:2)

使用Ansible,你应该定义所需的状态。周期。

这样做的正确方法是使用timezone模块:

- name: set timezone
  timezone:
    name: "{{ DesiredTimeZone }}"

无需通过shell跳过箍,注册,比较,打印......

如果您想将系统置于所需状态,只需运行playbook:

ansible-playbook -e DesiredTimeZone=Asia/Tokyo timezone_playbook.yml

Ansible将确保所有相关主机都拥有DesiredTimeZone

如果您只想检查系统是否符合所需状态,请使用--check开关:

ansible-playbook -e DesiredTimeZone=Asia/Tokyo --check timezone_playbook.yml

在这种情况下,Ansible只会在日志中打印当前状态应该更改的内容,以便成为所需状态,并且不做任何实际更改。

答案 1 :(得分:2)

我的以下答案可能不是您的解决方案。

  1. 如何为输出变量指定命令参数。
  2. ansible-playbook yourplaybook.yml -e output=/path/to/outputfile

    1. 如何从外部文件中包含DesiredTimeZone变量。
    2. vars_files: - external.yml

      完整的playbook.yml用于测试本地:

      • yourplaybook.yml

      - name: For testing hosts: localhost vars_files: - external.yml tasks: - name: check timezone tags: timezoneCheck register: timezoneCheckOut shell: timedatectl | grep -i "Time Zone" | awk -F":" '{print $2}' | awk --field-separator=" " '{print $1}'

      - debug: var=timezoneCheckOut.stdout

      - lineinfile: path: "{{ output }}" line: "Did not find {{ DesiredTimeZone }}" create: True state: present insertafter: EOF when: timezoneCheckOut.stdout != DesiredTimeZone

      • external.yml(与yourplaybook.yml放置相同的级别)

      --- DesiredTimeZone: "Asia/Tokyo"