Running Ansible task as a specific user

72

Solution 1

You're misunderstanding both settings there:

  • remote_user is an Ansible setting that controls the SSH user Ansible is using to connect: ssh ${REMOTE_USER}@remotehost

  • someusername ALL=(ALL) NOPASSWD:ALL is a sudo configuration that allows the user someusername to execute all commands in any host without a password. It does not allow anyone to issue commands as someusername though.

Ideally, you would login directly as the right user and that's what remote_user is all about. But usually you are only able to login as an administrative user (say, ubuntu) and have to sudo commands as another user (let's say scrapy). Then you should leave remote_user to the user that logs in and the add the following ansible properties to the job:

- name: log in as ubuntu and do something as scrapy
  remote_user: ubuntu
  sudo: true
  sudo_user: scrapy
  shell: do-something.sh

Solution 2

Note that after Ansible 1.9, the sudo wording was replaced with become, thus

sudo: yes
sudo_user: some_user

becomes (pun intended):

become: yes
become_user: some_user

See more specifics here: https://stackoverflow.com/a/22749788/402727

Also write this before the actual module (e.g. command or shell) you want to execute for it to take effect. At least in my experience it didn't work correctly if I have written become and become_user after the shell module.

- name: Example user change
  become: true
  become_user: '{{ user }}'
  shell: |
    ...
Share:
72

Related videos on Youtube

Thorsten Franz Brune
Author by

Thorsten Franz Brune

Updated on September 18, 2022

Comments

  • Thorsten Franz Brune
    Thorsten Franz Brune over 1 year

    I started Python and struggle on using __repr__ data outside of a class. Printing the data outputs a list with lists (exactly what I wanted to do), example: print(test) leads to:

    [['Food', '-10.15', '-15.89', '-50'], ['Clothing', '-25.55'], ['Auto', '-15']]
    

    My problem is: print(test[0]) leads to unexpected outputs, not:

    ['Food', '-10.15', '-15.89', '-50']
    

    rather than some data like:

    *************Food*************
    initial deposit        1000.00
    groceries               -10.15
    restaurant and more foo -15.89
    Transfer to Clothing    -50.00
    Total: 923.96
    ***********Clothing***********
    Transfer from Food       50.00
                            -25.55
    Total:  24.45
    *************Food*************
    initial deposit        1000.00
    groceries               -10.15
    restaurant and more foo -15.89
    Transfer to Clothing    -50.00
    Total: 923.96
    None
    .***********Business***********
    deposit                 900.00
                            -10.99
    
    class Category:
      def __init__(self, category):
        self.category = category
        self.balance = 0
        self.ledger = []
      def __repr__(self):
        b = []
        b.append(self.category)
        for obj in self.ledger:
          if str(obj['amount'])[0] == "-":
            b.append(str(obj['amount']))
        return str(b)
      def __str__(self):
        lengthTop = int((30 - len(str(self.category))) / 2)
        output = "*" * lengthTop + self.category + "*" * lengthTop
        for entry in self.ledger:
          if len(entry['description']) > 23:  
            x = slice(0, 23)
            output += "\n" + entry['description'][x] + ("{:7.2f}".format(entry['amount']))
          else:
            output += ("\n" + entry['description'] + (" " * (23 - int(len(entry['description'])))) + ("{:7.2f}".format(entry['amount']))) 
        output += "\n" + "Total:" + ("{:7.2f}".format(self.balance))
        return output
      def check_funds(self, amount):
        if amount > self.balance:
          return False
        else:
          return True
      def deposit(self, amount, description=""):
        self.balance += amount
        self.ledger.append({"amount": amount, "description": description})
      def withdraw(self, amount, description=""):
        if self.check_funds(amount) == True:
          self.balance -= amount
          self.ledger.append({"amount": -amount, "description": description})
          return True
        else:
          return False
      def get_balance(self):
        return self.balance
      def transfer(self, amount, newcategory):
        if self.check_funds(amount) == True:
          self.withdraw(amount, "Transfer to " + newcategory.category)
          newcategory.deposit(amount, "Transfer from " + self.category)
          return True
        else:
          return False
    def create_spend_chart(categories):
      test = categories
      print(test)
    
  • errata
    errata over 9 years
    I see. Thanks a lot for clarifying this! But how to run a specific task as a specific user then?
  • Capi Etheriel
    Capi Etheriel over 9 years
    Note that remote_user defaults to the current user in your local machine -- just as ssh does, actually.
  • errata
    errata over 9 years
    Alright, but with a setup like this I still get 'Missing sudo password' error. Is there a way to avoid asking for password for that specific user?
  • errata
    errata over 9 years
    I think I found the answer, adding the line to sudoers: ubuntu ALL=(someusername) NOPASSWD: ALL, but I have to think about the security behind this... Is there any other way except adding this line to sudoers?
  • Capi Etheriel
    Capi Etheriel over 9 years
    the proper way would be to let your remote user to login directly.
  • errata
    errata over 9 years
    Yeah, that was what I was thinking in the end, just to make those tasks which should be done as someusername as a playbook different than the one which is using ubuntu user. Can you maybe include your last comment in the answer so I can accept it?
  • Capi Etheriel
    Capi Etheriel over 9 years
    It was already there, now it's there with bold.