如何在lineinfile中使用转义字符

时间:2018-11-13 00:18:45

标签: ansible ansible-2.x

我正在写一部添加用户的剧本。

到目前为止,我明白了。

- name: Add user to sudoers
  hosts: all_hosts
  su: yes
  su_user: root
  tasks:
    - lineinfile: line='worker_temp ALL=(ALL) NOPASSWD: /bin/sh' dest='/etc/sudoers'

我能够添加用户,这是另一项任务。 我试图在sudoers文件中添加相同的用户。 失败

ERROR! Syntax Error while loading YAML.
  mapping values are not allowed here

at   - lineinfile: line="worker_temp ALL=(ALL) NOPASSWD: /bin/sh" dest="/etc/sudoers"
                                                       ^ here

我尝试通过添加转义引号,但随后将以下行附加在sudoers文件中

worker_temp ALL=(ALL) NOPASSWD':' /bin/sh

此行在''周围有:多余

我怎么只能得到

worker_temp ALL=(ALL) NOPASSWD: /bin/sh

谢谢。

1 个答案:

答案 0 :(得分:1)

仅当您实际引用标量时,才能转义引号,并且在您的示例中,键linenfile的值不是带引号的标量,因为它是值:

line='worker_temp ALL=(ALL) NOPASSWD: /bin/sh' dest='/etc/sudoers'

(尽管标量中有引号,但带引号的标量需要以单引号或双引号开始(和结束)。

只需将双引号引起来,将防止您的解析器将该行上的第二个:和第一个- lineinfile: "line='worker_temp ALL=(ALL) NOPASSWD: /bin/sh' dest='/etc/sudoers'" 误解为一个值指示符。

def printmenu():
    print("=" * 20)
    print("Welcome to Dons Bank")
    print("What can I do for you?")
    print("1 - Withdraw Funds")
    print("2 - Deposit Funds")
    print("3 - Show Balance")
    print("4 - Quit")
    print("=" * 20)

def main():
    myBalance = 1000
    userChoice = 0
#    invalidcharac = True
    printmenu()

    while True:
        try: 
            userChoice = int(input("Please choose one of the above options: "))
        except ValueError:
            print("Invalid option.  Please choose an option by entering 1, 2, 3, or 4.")
            continue

        if userChoice == 1:
            try:

                amount = int(input("Amount to withdraw: "))
                while myBalance - amount < 0:
                    print("Sorry: you don't have that much money in your account.")
                    amount = int(input("Amount to withdraw: "))
                myBalance = myBalance - amount
                print("New balance: ", myBalance)
            except:
                print("Invalid option. Reset to menu.")
                continue

        elif userChoice == 2:
            try:
                amount = int(input("Amount to deposit: "))
                myBalance = myBalance + amount
                print("New balance: ", myBalance)
            except:
                print("Invalid option. Reset to menu.")
                continue

        elif userChoice == 3:
            print("Your balance is: ", myBalance)
        elif userChoice == 4:
            break
        else:
            print("Invalid option. Please choose an option by entering 1, 2, 3, or 4.")
    print("Thank you. Goodbye!")

main()