如何使用Ansible任务编写'systemctl set-default graphical.target'而不使用shell/command模块?

6
我希望在Ansible中编写一个任务,执行以下命令:

"systemctl set-default graphical.target"

而不使用shell/command模块。

不确定"ansible.builtin.systemd"模块是否具有此选项。


有一个关于此事的已开放工单:https://github.com/ansible/ansible/issues/65785 - Zeitounator
3个回答

8

您可以使用command模块,并使用一些魔法来获得幂等解决方案。实际上,没有具体的模块,而且针对systemd模块的给定更改请求已关闭并未合并。

- name: "Get current systemd default"
  command: "systemctl get-default"
  changed_when: false
  register: systemdefault

- name: "Set default to graphical target"
  command: "systemctl set-default graphical.target"
  when: "'graphical' not in systemdefault.stdout"

当然,这需要使用命令。但是如果你知道需要使用它时,没有不使用命令的坏理由。虽然看起来不太好 - 好吧。但是最终,自定义模块在幕后也会执行相同的操作,而且对于这样一个“单一”的问题可能会有点复杂。实际上,“链接”解决方案也是一样的,但必须明确知道链接文件的位置(参见Debian)。


5
当您执行systemctl set-default graphical.target时,您可以看到以下日志。
Removed symlink /etc/systemd/system/default.target. 
Created symlink from /etc/systemd/system/default.target to /usr/lib/systemd/system/graphical.target.

然后您可以使用file模块创建符号链接,如下所示:

- name: Change default target
  hosts: all
  become: yes
  gather_facts: no

  tasks:
  - name: Change default target to graphical.target
    file:
      src: /usr/lib/systemd/system/graphical.target
      dest: /etc/systemd/system/default.target
      state: link

2
在Debian系统中,目标文件存储在/lib/systemd/system/目录下 - 是否有一种方法可以知道目标目录的位置而不需要硬编码它? - njh
1
这是一个糟糕的解决方案。它使用实现细节并且是特定于发行版的。我不明白为什么这是预期的答案。更好的方法是使用“前端”本身。在Ansible中调用systemctl get-default并注册输出。当输出包含非图形化时,则调用第二个命令systemctl set-default。这适用于所有发行版。 - TRW

0

@njh 我在寻找其他东西时刚刚发现了这个。 /lib/systemd 包含使用 APT 等安装的 systemd 文件,本地覆盖在 /etc/systemd 中,其中包括默认目标,因此如果您想更改默认目标,请像 @gary-lopez 建议的那样更改符号链接。

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Oct 23 20:00:36 2021 from 192.168.1.10
pi@penguin:~ $ ls -l /etc/systemd/system/default.target 
lrwxrwxrwx 1 root root 36 Feb 13  2020 /etc/systemd/system/default.target -> /lib/systemd/system/graphical.target
pi@penguin:~ $ ls -l /lib/systemd/system/default.target
lrwxrwxrwx 1 root root 16 Aug  6 17:38 /lib/systemd/system/default.target -> graphical.target
pi@penguin:~ $ 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接