如何在Ansible中执行多行shell脚本

7xllpg7q  于 2023-01-31  发布在  Shell
关注(0)|答案(5)|浏览(478)

现在我在ansible中使用shell脚本,如果它在多行中,可读性会更好

- name: iterate user groups
  shell: groupmod -o -g {{ item['guid'] }} {{ item['username'] }} ....more stuff to do
  with_items: "{{ users }}"

只是不确定如何在Ansible shell模块中允许多行脚本

pengsaosao

pengsaosao1#

Ansible在其剧本中使用YAML语法。YAML有许多块操作符:

  • >是一个折叠块运算符。也就是说,它通过空格将多行连接在一起。语法如下:
key: >
  This text
  has multiple
  lines

会将值This text has multiple lines\n赋给key

  • |字符是一个文字块运算符。这可能是多行shell脚本所需要的。语法如下:
key: |
  This text
  has multiple
  lines

会将This text\nhas multiple\nlines\n赋值给key
您可以将其用于如下多行shell脚本:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

有一点需要注意:Ansible对shell命令的参数进行了一些笨拙的操作,因此,虽然上面的命令通常会按预期工作,但下面的命令不会:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible实际上会呈现带有前导空格的文本,这意味着shell永远不会在行首找到字符串EOF,您可以通过使用cmd参数来避免Ansible的无用启发式:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF
xxhby3vn

xxhby3vn2#

尝试使用ansible2.0.0.2:

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

shell命令被压缩为一行,如ls --color /home所示
参考文献(2021年访问):https://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html ==〉页面中的搜索表单“多行”。

qlvxas9a

qlvxas9a3#

在EOF分隔符前添加一个空格可以避免cmd:

- shell: |
    cat <<' EOF'
    This is a test.
    EOF
zpf6vheq

zpf6vheq4#

我更喜欢这种语法,因为它允许设置shell的配置参数:

---
- name: an example
  shell:
    cmd: |
      docker build -t current_dir .
      echo "Hello World"
      date

    chdir: /home/vagrant/
nkkqxpd9

nkkqxpd95#

您可以使用lineinfile集合附加文件,使用属性create创建文件(如果不存在),使用"|".

- name: Add a line to a file if the file does not exist
  ansible.builtin.lineinfile:
    path: ~/.ssh/config
    line: |
      Host {{item.COMPONENT}} {{item.COMPONENT}}.{{ZONE}}
        HostName {{r53_var_one.resource_record_sets[0].resource_records[0].value}}
        User centos
        Port 22
        IdentityFile ~/.ssh/key.pem
        StrictHostKeyChecking no
    create: yes
    mode: '0600'

相关问题