Search code examples
authenticationaws-cloudformation

Adding a user during startup of a machine using CloudFormation


I am trying to create a user using CloudFormation after startup of a Linux machine. I use the following code to do so:

  Metadata:
  AWS::CloudFormation::Init:
    config:
      groups:
        ansible: {}
      users:
        ansible:
          groups:
            - "ansible"
          homeDir: "/home/ansible"
      files:
        /home/ansible/.ssh/authorized_keys:
          content: !Sub |
            '{{ resolve:secretsmanager:
              arn:aws:secretsmanager:eu-central-1:account:secret:secretname:
                SecretString:
                  secretstringpath }}'
          mode: "000644"
          owner: "ansible"
          group: "ansible"
Properties:
  UserData:
    Fn::Base64: !Sub |
      #!/bin/bash -xe
      yum update -y
      yum install -y aws-cfn-bootstrap
      /opt/aws/bin/cfn-init -v \
        --stack ${AWS::StackName} \
        --resource LinuxEC2Instance \
        --region ${AWS::Region}

However, during startup I get the following error message:

[ 96.72999017] cloud-init[2959]: Error occurred during build: Failed to add user ansible

What does this error mean? It does not seem to work as expected the way I do it ...


Solution

  • Before you can assign users to custom groups, you have to create such groups.

    For that there is groups option in AWS::CloudFormation::Init.

    For example:

    groups: 
      ansible: {}