在Ansible中,您可以使用chdir
关键字将Ansible切换到特定目录以运行命令。下面是一个示例代码:
- name: Run command in a specific directory
hosts: your_host
tasks:
- name: Change directory
become: true
become_user: your_user
command: cd /path/to/your/directory
- name: Run command in the directory
become: true
become_user: your_user
command: your_command
在上面的示例中,我们首先使用command
模块将Ansible切换到特定目录,然后使用另一个command
模块在该目录中运行命令。
请注意,become
和become_user
关键字用于提升权限并切换到特定用户。根据您的需求,您可以选择使用它们。
另外,您还可以使用shell
模块来运行多个命令,而不是分开使用两个command
模块。示例代码如下:
- name: Run command in a specific directory
hosts: your_host
tasks:
- name: Run command in the directory
become: true
become_user: your_user
shell: |
cd /path/to/your/directory
your_command
上述代码中的shell
模块将两个命令放在一个脚本中,并在指定目录中运行。
希望这可以帮助到您!