From a597819e8a964936e6bb9b45c6bcf084333502ad Mon Sep 17 00:00:00 2001 From: Dezo2018 Date: Wed, 21 Sep 2022 17:49:31 -0400 Subject: [PATCH 1/5] Lab 10-kms --- 10-kms/Practice-10.1/PlaintextFile | 1 + 10-kms/Practice-10.1/cmk_key.yml | 55 ++++++++++++++++++ 10-kms/Practice-10.1/encryptedFile | Bin 0 -> 174 bytes 10-kms/Practice-10.1/file.txt | 1 + 10-kms/Practice-10.1/scripts | 14 +++++ 10-kms/Practice-10.2/NewFile.txt | 1 + 10-kms/Practice-10.2/go.mod | 10 ++++ 10-kms/Practice-10.2/go.sum | 22 +++++++ .../Practice-10.2/s3_client_side_download.go | 55 ++++++++++++++++++ 10-kms/Practice-10.2/s3_client_side_upload.go | 55 ++++++++++++++++++ 10 files changed, 214 insertions(+) create mode 100644 10-kms/Practice-10.1/PlaintextFile create mode 100644 10-kms/Practice-10.1/cmk_key.yml create mode 100644 10-kms/Practice-10.1/encryptedFile create mode 100644 10-kms/Practice-10.1/file.txt create mode 100644 10-kms/Practice-10.1/scripts create mode 100644 10-kms/Practice-10.2/NewFile.txt create mode 100644 10-kms/Practice-10.2/go.mod create mode 100644 10-kms/Practice-10.2/go.sum create mode 100644 10-kms/Practice-10.2/s3_client_side_download.go create mode 100644 10-kms/Practice-10.2/s3_client_side_upload.go diff --git a/10-kms/Practice-10.1/PlaintextFile b/10-kms/Practice-10.1/PlaintextFile new file mode 100644 index 00000000..6675f302 --- /dev/null +++ b/10-kms/Practice-10.1/PlaintextFile @@ -0,0 +1 @@ +This is my secret file \ No newline at end of file diff --git a/10-kms/Practice-10.1/cmk_key.yml b/10-kms/Practice-10.1/cmk_key.yml new file mode 100644 index 00000000..704bbc4c --- /dev/null +++ b/10-kms/Practice-10.1/cmk_key.yml @@ -0,0 +1,55 @@ +Description: AWS CMK Key + +Resources: + myKey: + Type: 'AWS::KMS::Key' + Properties: + Description: A symmetric encryption KMS key + EnableKeyRotation: true + PendingWindowInDays: 20 + KeyPolicy: + Version: 2012-10-17 + Id: key-default-1 + Statement: + - Sid: Enable IAM User Permissions + Effect: Allow + Principal: + AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root" + Action: 'kms:*' + Resource: '*' + - Sid: Allow administration of the key + Effect: Allow + Principal: + AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/desmond.ndambi.labs" + Action: + - 'kms:Create*' + - 'kms:Describe*' + - 'kms:Enable*' + - 'kms:List*' + - 'kms:Put*' + - 'kms:Update*' + - 'kms:Revoke*' + - 'kms:Disable*' + - 'kms:Get*' + - 'kms:Delete*' + - 'kms:ScheduleKeyDeletion' + - 'kms:CancelKeyDeletion' + Resource: '*' + - Sid: Allow use of the key + Effect: Allow + Principal: + AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/desmond.ndambi.labs" + Action: + - 'kms:DescribeKey' + - 'kms:Encrypt' + - 'kms:Decrypt' + - 'kms:ReEncrypt*' + - 'kms:GenerateDataKey' + - 'kms:GenerateDataKeyWithoutPlaintext' + Resource: '*' + + myAlias: + Type: 'AWS::KMS::Alias' + Properties: + AliasName: alias/ndambi + TargetKeyId: !Ref myKey diff --git a/10-kms/Practice-10.1/encryptedFile b/10-kms/Practice-10.1/encryptedFile new file mode 100644 index 0000000000000000000000000000000000000000..4630c9e4002f05385c117521b5cb0c22ac647e70 GIT binary patch literal 174 zcmZQ%Vq&PcB71b>S3|Z-2d=ss8{P2TaO9D})we2U??Niyzg{@oP@M6}vr4XZz6IN+ zc0PCHcv!xJfq|jKpoooAtIebBJ1-+U+k#YsWF|%igE)j3qk$Y7XF{6?V=6NXqn?2v z3(vIeQ-t3f`FAcqDM*EhQJ}$a+WH;W@`Qd~bjbW_d0g64DDZbj({&fdkp93v<18Pa Xd4GOX{}wiOjPWZ`6W+CSxjrudY>Pw4 literal 0 HcmV?d00001 diff --git a/10-kms/Practice-10.1/file.txt b/10-kms/Practice-10.1/file.txt new file mode 100644 index 00000000..6675f302 --- /dev/null +++ b/10-kms/Practice-10.1/file.txt @@ -0,0 +1 @@ +This is my secret file \ No newline at end of file diff --git a/10-kms/Practice-10.1/scripts b/10-kms/Practice-10.1/scripts new file mode 100644 index 00000000..f624bfba --- /dev/null +++ b/10-kms/Practice-10.1/scripts @@ -0,0 +1,14 @@ +aws kms encrypt \ + --key-id fbc58ad0-2bac-40fe-96ee-5ebd24d2f006 \ + --plaintext fileb://file.txt \ + --output text \ + --query CiphertextBlob | base64 \ + --decode > encryptedFile + +aws kms decrypt \ + --ciphertext-blob fileb://encryptedFile \ + --key-id fbc58ad0-2bac-40fe-96ee-5ebd24d2f006 \ + --output text \ + --query Plaintext | base64 \ + --decode > PlaintextFile + diff --git a/10-kms/Practice-10.2/NewFile.txt b/10-kms/Practice-10.2/NewFile.txt new file mode 100644 index 00000000..158a0601 --- /dev/null +++ b/10-kms/Practice-10.2/NewFile.txt @@ -0,0 +1 @@ +Test Client-Side encryption diff --git a/10-kms/Practice-10.2/go.mod b/10-kms/Practice-10.2/go.mod new file mode 100644 index 00000000..d6845094 --- /dev/null +++ b/10-kms/Practice-10.2/go.mod @@ -0,0 +1,10 @@ +module kms + +go 1.19 + +require ( + github.com/aws/aws-sdk-go v1.44.103 // indirect + github.com/aws/aws-sdk-go-v2 v1.16.16 // indirect + github.com/aws/smithy-go v1.13.3 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect +) diff --git a/10-kms/Practice-10.2/go.sum b/10-kms/Practice-10.2/go.sum new file mode 100644 index 00000000..70c1397e --- /dev/null +++ b/10-kms/Practice-10.2/go.sum @@ -0,0 +1,22 @@ +github.com/aws/aws-sdk-go v1.44.103 h1:tbhBHKgiZSIUkG8FcHy3wYKpPVvp65Wn7ZiX0B8phpY= +github.com/aws/aws-sdk-go v1.44.103/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= +github.com/aws/aws-sdk-go-v2 v1.16.16 h1:M1fj4FE2lB4NzRb9Y0xdWsn2P0+2UHVxwKyOa4YJNjk= +github.com/aws/aws-sdk-go-v2 v1.16.16/go.mod h1:SwiyXi/1zTUZ6KIAmLK5V5ll8SiURNUYOqTerZPaF9k= +github.com/aws/smithy-go v1.13.3 h1:l7LYxGuzK6/K+NzJ2mC+VvLUbae0sL3bXU//04MkmnA= +github.com/aws/smithy-go v1.13.3/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/10-kms/Practice-10.2/s3_client_side_download.go b/10-kms/Practice-10.2/s3_client_side_download.go new file mode 100644 index 00000000..096e6e33 --- /dev/null +++ b/10-kms/Practice-10.2/s3_client_side_download.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3crypto" + "os" +) + +var ( + bucket = "kms-bucket-ndambi" + key = "clientside.txt" +) + +func main() { + sess := session.New(&aws.Config{ + Region: aws.String("us-east-1"),}) + + client := s3crypto.NewDecryptionClient(sess) + + input := &s3.GetObjectInput{ + Bucket: &bucket, + Key: &key, + } + + result, err := client.GetObject(input) + // Aside from the S3 errors, here is a list of decryption client errors: + // * InvalidWrapAlgorithmError - returned on an unsupported Wrap algorithm + // * InvalidCEKAlgorithmError - returned on an unsupported CEK algorithm + // * V1NotSupportedError - the SDK doesn’t support v1 because security is an issue for AES ECB + // These errors don’t necessarily mean there’s something wrong. They just tell us we couldn't decrypt some data. + // Users can choose to log this and then continue decrypting the data that they can, or simply return the error. + if err != nil { + log.Fatal(err) + } + + // Let's read the whole body from the response + b, err := ioutil.ReadAll(result.Body) + if err != nil { + log.Fatal(err) + } + //fmt.Println(string(b)) + + file, err := os.Create("NewFile.txt") + if err != nil { + fmt.Println(err) + return + } + fmt.Fprintf(file, "%v\n", string(b)) +} diff --git a/10-kms/Practice-10.2/s3_client_side_upload.go b/10-kms/Practice-10.2/s3_client_side_upload.go new file mode 100644 index 00000000..7f885b6b --- /dev/null +++ b/10-kms/Practice-10.2/s3_client_side_upload.go @@ -0,0 +1,55 @@ +/* +Licensed under the MIT-0 license https://github.com/aws/mit-0 +*/ +package main + +import ( + "log" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/kms" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/aws/aws-sdk-go/service/s3/s3crypto" +) + +var ( + cmkId = "fbc58ad0-2bac-40fe-96ee-5ebd24d2f006" + bucket = "kms-bucket-ndambi" + key = "clientside.txt" +) + +func main() { + sess, err := session.NewSession(&aws.Config{ + Region: aws.String("us-east-1"), + Credentials: credentials.NewSharedCredentials("", "default"), + }) + // This is our key wrap handler, used to generate cipher keys and IVs for + // our cipher builder. Using an IV allows more “spontaneous” encryption. + // The IV makes it more difficult for hackers to use dictionary attacks. + // The key wrap handler behaves as the master key. Without it, you can’t + // encrypt or decrypt the data. + keywrap := s3crypto.NewKMSKeyGenerator(kms.New(sess), cmkId) + // This is our content cipher builder, used to instantiate new ciphers + // that enable us to encrypt or decrypt the payload. + builder := s3crypto.AESGCMContentCipherBuilder(keywrap) + // Let's create our crypto client! + client := s3crypto.NewEncryptionClient(sess, builder) + + input := &s3.PutObjectInput{ + Bucket: &bucket, + Key: &key, + Body: strings.NewReader("Test Client-Side encryption"), + } + + _, err = client.PutObject(input) + // What to expect as errors? You can expect any sort of S3 errors, http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html. + // The s3crypto client can also return some errors: + // * MissingCMKIDError - when using AWS KMS, the user must specify their key's ARN + if err != nil { + log.Fatal(err) + } +} + From c9056754893bbf19830f5f0c788e9f8d1e9af36f Mon Sep 17 00:00:00 2001 From: Dezo2018 Date: Thu, 22 Sep 2022 10:57:05 -0400 Subject: [PATCH 2/5] removing files --- 10-kms/Practice-10.1/PlaintextFile | 1 - 10-kms/Practice-10.1/cmk_key.yml | 55 ------------------ 10-kms/Practice-10.1/encryptedFile | Bin 174 -> 0 bytes 10-kms/Practice-10.1/file.txt | 1 - 10-kms/Practice-10.1/scripts | 14 ----- 10-kms/Practice-10.2/NewFile.txt | 1 - 10-kms/Practice-10.2/go.mod | 10 ---- 10-kms/Practice-10.2/go.sum | 22 ------- .../Practice-10.2/s3_client_side_download.go | 55 ------------------ 10-kms/Practice-10.2/s3_client_side_upload.go | 55 ------------------ 10 files changed, 214 deletions(-) delete mode 100644 10-kms/Practice-10.1/PlaintextFile delete mode 100644 10-kms/Practice-10.1/cmk_key.yml delete mode 100644 10-kms/Practice-10.1/encryptedFile delete mode 100644 10-kms/Practice-10.1/file.txt delete mode 100644 10-kms/Practice-10.1/scripts delete mode 100644 10-kms/Practice-10.2/NewFile.txt delete mode 100644 10-kms/Practice-10.2/go.mod delete mode 100644 10-kms/Practice-10.2/go.sum delete mode 100644 10-kms/Practice-10.2/s3_client_side_download.go delete mode 100644 10-kms/Practice-10.2/s3_client_side_upload.go diff --git a/10-kms/Practice-10.1/PlaintextFile b/10-kms/Practice-10.1/PlaintextFile deleted file mode 100644 index 6675f302..00000000 --- a/10-kms/Practice-10.1/PlaintextFile +++ /dev/null @@ -1 +0,0 @@ -This is my secret file \ No newline at end of file diff --git a/10-kms/Practice-10.1/cmk_key.yml b/10-kms/Practice-10.1/cmk_key.yml deleted file mode 100644 index 704bbc4c..00000000 --- a/10-kms/Practice-10.1/cmk_key.yml +++ /dev/null @@ -1,55 +0,0 @@ -Description: AWS CMK Key - -Resources: - myKey: - Type: 'AWS::KMS::Key' - Properties: - Description: A symmetric encryption KMS key - EnableKeyRotation: true - PendingWindowInDays: 20 - KeyPolicy: - Version: 2012-10-17 - Id: key-default-1 - Statement: - - Sid: Enable IAM User Permissions - Effect: Allow - Principal: - AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root" - Action: 'kms:*' - Resource: '*' - - Sid: Allow administration of the key - Effect: Allow - Principal: - AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/desmond.ndambi.labs" - Action: - - 'kms:Create*' - - 'kms:Describe*' - - 'kms:Enable*' - - 'kms:List*' - - 'kms:Put*' - - 'kms:Update*' - - 'kms:Revoke*' - - 'kms:Disable*' - - 'kms:Get*' - - 'kms:Delete*' - - 'kms:ScheduleKeyDeletion' - - 'kms:CancelKeyDeletion' - Resource: '*' - - Sid: Allow use of the key - Effect: Allow - Principal: - AWS: !Sub "arn:aws:iam::${AWS::AccountId}:user/desmond.ndambi.labs" - Action: - - 'kms:DescribeKey' - - 'kms:Encrypt' - - 'kms:Decrypt' - - 'kms:ReEncrypt*' - - 'kms:GenerateDataKey' - - 'kms:GenerateDataKeyWithoutPlaintext' - Resource: '*' - - myAlias: - Type: 'AWS::KMS::Alias' - Properties: - AliasName: alias/ndambi - TargetKeyId: !Ref myKey diff --git a/10-kms/Practice-10.1/encryptedFile b/10-kms/Practice-10.1/encryptedFile deleted file mode 100644 index 4630c9e4002f05385c117521b5cb0c22ac647e70..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 174 zcmZQ%Vq&PcB71b>S3|Z-2d=ss8{P2TaO9D})we2U??Niyzg{@oP@M6}vr4XZz6IN+ zc0PCHcv!xJfq|jKpoooAtIebBJ1-+U+k#YsWF|%igE)j3qk$Y7XF{6?V=6NXqn?2v z3(vIeQ-t3f`FAcqDM*EhQJ}$a+WH;W@`Qd~bjbW_d0g64DDZbj({&fdkp93v<18Pa Xd4GOX{}wiOjPWZ`6W+CSxjrudY>Pw4 diff --git a/10-kms/Practice-10.1/file.txt b/10-kms/Practice-10.1/file.txt deleted file mode 100644 index 6675f302..00000000 --- a/10-kms/Practice-10.1/file.txt +++ /dev/null @@ -1 +0,0 @@ -This is my secret file \ No newline at end of file diff --git a/10-kms/Practice-10.1/scripts b/10-kms/Practice-10.1/scripts deleted file mode 100644 index f624bfba..00000000 --- a/10-kms/Practice-10.1/scripts +++ /dev/null @@ -1,14 +0,0 @@ -aws kms encrypt \ - --key-id fbc58ad0-2bac-40fe-96ee-5ebd24d2f006 \ - --plaintext fileb://file.txt \ - --output text \ - --query CiphertextBlob | base64 \ - --decode > encryptedFile - -aws kms decrypt \ - --ciphertext-blob fileb://encryptedFile \ - --key-id fbc58ad0-2bac-40fe-96ee-5ebd24d2f006 \ - --output text \ - --query Plaintext | base64 \ - --decode > PlaintextFile - diff --git a/10-kms/Practice-10.2/NewFile.txt b/10-kms/Practice-10.2/NewFile.txt deleted file mode 100644 index 158a0601..00000000 --- a/10-kms/Practice-10.2/NewFile.txt +++ /dev/null @@ -1 +0,0 @@ -Test Client-Side encryption diff --git a/10-kms/Practice-10.2/go.mod b/10-kms/Practice-10.2/go.mod deleted file mode 100644 index d6845094..00000000 --- a/10-kms/Practice-10.2/go.mod +++ /dev/null @@ -1,10 +0,0 @@ -module kms - -go 1.19 - -require ( - github.com/aws/aws-sdk-go v1.44.103 // indirect - github.com/aws/aws-sdk-go-v2 v1.16.16 // indirect - github.com/aws/smithy-go v1.13.3 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect -) diff --git a/10-kms/Practice-10.2/go.sum b/10-kms/Practice-10.2/go.sum deleted file mode 100644 index 70c1397e..00000000 --- a/10-kms/Practice-10.2/go.sum +++ /dev/null @@ -1,22 +0,0 @@ -github.com/aws/aws-sdk-go v1.44.103 h1:tbhBHKgiZSIUkG8FcHy3wYKpPVvp65Wn7ZiX0B8phpY= -github.com/aws/aws-sdk-go v1.44.103/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= -github.com/aws/aws-sdk-go-v2 v1.16.16 h1:M1fj4FE2lB4NzRb9Y0xdWsn2P0+2UHVxwKyOa4YJNjk= -github.com/aws/aws-sdk-go-v2 v1.16.16/go.mod h1:SwiyXi/1zTUZ6KIAmLK5V5ll8SiURNUYOqTerZPaF9k= -github.com/aws/smithy-go v1.13.3 h1:l7LYxGuzK6/K+NzJ2mC+VvLUbae0sL3bXU//04MkmnA= -github.com/aws/smithy-go v1.13.3/go.mod h1:Tg+OJXh4MB2R/uN61Ko2f6hTZwB/ZYGOtib8J3gBHzA= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= -github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/10-kms/Practice-10.2/s3_client_side_download.go b/10-kms/Practice-10.2/s3_client_side_download.go deleted file mode 100644 index 096e6e33..00000000 --- a/10-kms/Practice-10.2/s3_client_side_download.go +++ /dev/null @@ -1,55 +0,0 @@ -package main - -import ( - "fmt" - "io/ioutil" - "log" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3crypto" - "os" -) - -var ( - bucket = "kms-bucket-ndambi" - key = "clientside.txt" -) - -func main() { - sess := session.New(&aws.Config{ - Region: aws.String("us-east-1"),}) - - client := s3crypto.NewDecryptionClient(sess) - - input := &s3.GetObjectInput{ - Bucket: &bucket, - Key: &key, - } - - result, err := client.GetObject(input) - // Aside from the S3 errors, here is a list of decryption client errors: - // * InvalidWrapAlgorithmError - returned on an unsupported Wrap algorithm - // * InvalidCEKAlgorithmError - returned on an unsupported CEK algorithm - // * V1NotSupportedError - the SDK doesn’t support v1 because security is an issue for AES ECB - // These errors don’t necessarily mean there’s something wrong. They just tell us we couldn't decrypt some data. - // Users can choose to log this and then continue decrypting the data that they can, or simply return the error. - if err != nil { - log.Fatal(err) - } - - // Let's read the whole body from the response - b, err := ioutil.ReadAll(result.Body) - if err != nil { - log.Fatal(err) - } - //fmt.Println(string(b)) - - file, err := os.Create("NewFile.txt") - if err != nil { - fmt.Println(err) - return - } - fmt.Fprintf(file, "%v\n", string(b)) -} diff --git a/10-kms/Practice-10.2/s3_client_side_upload.go b/10-kms/Practice-10.2/s3_client_side_upload.go deleted file mode 100644 index 7f885b6b..00000000 --- a/10-kms/Practice-10.2/s3_client_side_upload.go +++ /dev/null @@ -1,55 +0,0 @@ -/* -Licensed under the MIT-0 license https://github.com/aws/mit-0 -*/ -package main - -import ( - "log" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/kms" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/aws/aws-sdk-go/service/s3/s3crypto" -) - -var ( - cmkId = "fbc58ad0-2bac-40fe-96ee-5ebd24d2f006" - bucket = "kms-bucket-ndambi" - key = "clientside.txt" -) - -func main() { - sess, err := session.NewSession(&aws.Config{ - Region: aws.String("us-east-1"), - Credentials: credentials.NewSharedCredentials("", "default"), - }) - // This is our key wrap handler, used to generate cipher keys and IVs for - // our cipher builder. Using an IV allows more “spontaneous” encryption. - // The IV makes it more difficult for hackers to use dictionary attacks. - // The key wrap handler behaves as the master key. Without it, you can’t - // encrypt or decrypt the data. - keywrap := s3crypto.NewKMSKeyGenerator(kms.New(sess), cmkId) - // This is our content cipher builder, used to instantiate new ciphers - // that enable us to encrypt or decrypt the payload. - builder := s3crypto.AESGCMContentCipherBuilder(keywrap) - // Let's create our crypto client! - client := s3crypto.NewEncryptionClient(sess, builder) - - input := &s3.PutObjectInput{ - Bucket: &bucket, - Key: &key, - Body: strings.NewReader("Test Client-Side encryption"), - } - - _, err = client.PutObject(input) - // What to expect as errors? You can expect any sort of S3 errors, http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html. - // The s3crypto client can also return some errors: - // * MissingCMKIDError - when using AWS KMS, the user must specify their key's ARN - if err != nil { - log.Fatal(err) - } -} - From 70c02725705f84068eba7bc085ee774c79f420fd Mon Sep 17 00:00:00 2001 From: Dezo2018 Date: Thu, 29 Sep 2022 13:46:32 -0400 Subject: [PATCH 3/5] Practice-13.1 --- 13-ECS/Practice-13.1/commands.txt | 14 +++++++ 13-ECS/Practice-13.1/ecr.yml | 63 +++++++++++++++++++++++++++++ 13-ECS/Practice-13.1/parameter.json | 6 +++ 3 files changed, 83 insertions(+) create mode 100644 13-ECS/Practice-13.1/commands.txt create mode 100644 13-ECS/Practice-13.1/ecr.yml create mode 100644 13-ECS/Practice-13.1/parameter.json diff --git a/13-ECS/Practice-13.1/commands.txt b/13-ECS/Practice-13.1/commands.txt new file mode 100644 index 00000000..8f1a27b2 --- /dev/null +++ b/13-ECS/Practice-13.1/commands.txt @@ -0,0 +1,14 @@ +#LOGIN USING get-login-password +aws ecr get-login-password --region us-east-1 --profile labs | docker login --username AWS --password-stdin 324320755747.dkr.ecr.us-east-1.amazonaws.com + +docker tag nginx:latest 324320755747.dkr.ecr.us-east-1.amazonaws.com/ecr:latest + +docker push 324320755747.dkr.ecr.us-east-1.amazonaws.com/ecr:latest + +# LOGIN USING get-authorization-token +TOKEN=$(aws ecr get-authorization-token --profile labs --output text --query 'authorizationData[].authorizationToken') + +curl -i -H "Authorization: Basic $TOKEN" https://324320755747.dkr.ecr.us-east-1.amazonaws.com/v2/ecr/tags/list + +# Run the image +docker run --rm -it 324320755747.dkr.ecr.us-east-1.amazonaws.com/ecr:latest diff --git a/13-ECS/Practice-13.1/ecr.yml b/13-ECS/Practice-13.1/ecr.yml new file mode 100644 index 00000000..3d6f5557 --- /dev/null +++ b/13-ECS/Practice-13.1/ecr.yml @@ -0,0 +1,63 @@ +Description: An ECR Repository + +Parameters: + repositoryName: + Description: Name for the ECR Repository + Type: String + +Resources: + MyRepository: + Type: AWS::ECR::Repository + Properties: + RepositoryName: !Sub ${repositoryName} + ImageScanningConfiguration: + ScanOnPush: true + RepositoryPolicyText: + Version: "2012-10-17" + Statement: + - + Sid: AllowPushPull + Effect: Allow + Principal: + AWS: + - !Sub "arn:aws:iam::${AWS::AccountId}:user/desmond.ndambi.labs" + Action: + - "ecr:GetDownloadUrlForLayer" + - "ecr:BatchGetImage" + - "ecr:BatchCheckLayerAvailability" + - "ecr:PutImage" + - "ecr:InitiateLayerUpload" + - "ecr:UploadLayerPart" + - "ecr:CompleteLayerUpload" + LifecyclePolicy: + LifecyclePolicyText: | + { + "rules": [ + { + "rulePriority": 2, + "description": "Expire images after a month", + "selection": { + "tagStatus": "any", + "countType": "sinceImagePushed", + "countUnit": "days", + "countNumber": 30 + }, + "action": { "type": "expire" } + }, + { + "rulePriority": 1, + "description": "Keeps only one untagged image", + "selection": { + "tagStatus": "untagged", + "countType": "imageCountMoreThan", + "countNumber": 1 + }, + "action": { "type": "expire" } + } + ] + } + +Outputs: + MyRepository: + Description: The URI of the Repository + Value: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${repositoryName}" diff --git a/13-ECS/Practice-13.1/parameter.json b/13-ECS/Practice-13.1/parameter.json new file mode 100644 index 00000000..f7b9d52f --- /dev/null +++ b/13-ECS/Practice-13.1/parameter.json @@ -0,0 +1,6 @@ +[ + { + "ParameterKey": "repositoryName", + "ParameterValue": "ecr" + } +] \ No newline at end of file From 27aab348588e8dd368bc896d274cdba661be3972 Mon Sep 17 00:00:00 2001 From: Dezo2018 Date: Thu, 29 Sep 2022 14:17:37 -0400 Subject: [PATCH 4/5] ecs-fargate --- 13-ECS/Practice-13.3/ecs-fargate.yml | 249 +++++++++++++++++++++++++++ 13-ECS/Practice-13.3/parameter.json | 6 + 2 files changed, 255 insertions(+) create mode 100644 13-ECS/Practice-13.3/ecs-fargate.yml create mode 100644 13-ECS/Practice-13.3/parameter.json diff --git a/13-ECS/Practice-13.3/ecs-fargate.yml b/13-ECS/Practice-13.3/ecs-fargate.yml new file mode 100644 index 00000000..a94a3822 --- /dev/null +++ b/13-ECS/Practice-13.3/ecs-fargate.yml @@ -0,0 +1,249 @@ +Description: An ECS Fargate Cluster + +Parameters: + Name: + Description: Name of the Repository + Type: String + ECRRepositoryName: + Description: The name of the repository on Github + Type: String + Default: ecr + ImageTag: + Description: The Image tag in the repoitory (e.g 2.xx, latest) + Type: String + Default: latest + +Mappings: + SubnetConfig: + VPC: + CIDR: '10.0.0.0/16' + PublicSubnet1: + CIDR: '10.0.0.0/24' + PublicSubnet2: + CIDR: '10.0.1.0/24' + +Resources: + VPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: !FindInMap ['SubnetConfig', 'VPC', 'CIDR'] + EnableDnsHostnames: true + EnableDnsSupport: true + PublicSubnetOne: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: {Ref: 'AWS::Region'} + VpcId: !Ref 'VPC' + CidrBlock: !FindInMap ['SubnetConfig', 'PublicSubnet1', 'CIDR'] + MapPublicIpOnLaunch: true + PublicSubnetTwo: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: {Ref: 'AWS::Region'} + VpcId: !Ref 'VPC' + CidrBlock: !FindInMap ['SubnetConfig', 'PublicSubnet2', 'CIDR'] + MapPublicIpOnLaunch: true + InternetGateway: + Type: AWS::EC2::InternetGateway + GatewayAttachement: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + VpcId: !Ref 'VPC' + InternetGatewayId: !Ref 'InternetGateway' + PublicRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref 'VPC' + PublicRoute: + Type: AWS::EC2::Route + DependsOn: GatewayAttachement + Properties: + RouteTableId: !Ref 'PublicRouteTable' + DestinationCidrBlock: '0.0.0.0/0' + GatewayId: !Ref 'InternetGateway' + PublicSubnetOneRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PublicSubnetOne + RouteTableId: !Ref PublicRouteTable + PublicSubnetTwoRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PublicSubnetTwo + RouteTableId: !Ref PublicRouteTable + + # ECS Cluster Resources + ECSCluster: + Type: AWS::ECS::Cluster + Properties: + ClusterName: !Sub "${Name}-arnoldrx" + LBSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: ECS Security Group + VpcId: !Ref 'VPC' + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: 0.0.0.0/0 + LBSecurityGroupEgress: + Type: AWS::EC2::SecurityGroupEgress + Properties: + GroupId: + Fn::GetAtt: + - LBSecurityGroup + - GroupId + IpProtocol: tcp + Description: Load balancer to target + DestinationSecurityGroupId: + Fn::GetAtt: + - ServiceSecurityGroup + - GroupId + FromPort: 80 + ToPort: 80 + ServiceSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: ECS/MyApp/Service/SecurityGroup + VpcId: !Ref VPC + SecurityGroupEgress: + - CidrIp: 0.0.0.0/0 + Description: Allow all outbound traffic by default + IpProtocol: "-1" + ServiceSecurityGroupIngress: + Type: AWS::EC2::SecurityGroupIngress + Properties: + IpProtocol: tcp + Description: Load balancer to target + FromPort: 80 + GroupId: + Fn::GetAtt: + - ServiceSecurityGroup + - GroupId + SourceSecurityGroupId: + Fn::GetAtt: + - LBSecurityGroup + - GroupId + ToPort: 80 + ECSALB: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + Scheme: internet-facing + Type: application + Subnets: + - !Ref PublicSubnetOne + - !Ref PublicSubnetTwo + SecurityGroups: + - Fn::GetAtt: + - LBSecurityGroup + - GroupId + DependsOn: + - PublicRoute + LBListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + DefaultActions: + - TargetGroupArn: !Ref LBTargetGroup + Type: forward + LoadBalancerArn: !Ref ECSALB + Port: 80 + Protocol: HTTP + LBTargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + Port: 80 + Protocol: HTTP + TargetType: ip + VpcId: !Ref VPC + TaskDefTaskRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: ecs-tasks.amazonaws.com + Version: "2012-10-17" + TaskDefExecutionRole: + Type: AWS::IAM::Role + Properties: + RoleName: "TaskDefExecutionRole" + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: ecs-tasks.amazonaws.com + Version: "2012-10-17" + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" + TaskDefinition: + Type: AWS::ECS::TaskDefinition + Properties: + RequiresCompatibilities: + - "FARGATE" + ContainerDefinitions: + - Name: "nginx" + Image: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ECRRepositoryName}:${ImageTag}" + Cpu: "128" + PortMappings: + - ContainerPort: "80" + Protocol: "tcp" + HostPort: "80" + Memory: "256" + Essential: "true" + ExecutionRoleArn: !Ref TaskDefExecutionRole + NetworkMode: "awsvpc" + Cpu: "256" + Memory: "512" + RuntimePlatform: + { + "OperatingSystemFamily": "LINUX", + "CpuArchitecture": "X86_64" + } + ECSService: + Type: AWS::ECS::Service + DependsOn: + - ECSALB + Properties: + ServiceName: "ECSService" + Cluster: !Ref ECSCluster + DeploymentConfiguration: + DeploymentCircuitBreaker: + { + "Enable" : "true", + "Rollback" : "true" + } + MaximumPercent: "200" + MinimumHealthyPercent: "100" + DesiredCount: "1" + HealthCheckGracePeriodSeconds: "200" + LaunchType: "FARGATE" + LoadBalancers: + - ContainerName: "nginx" + ContainerPort: "80" + TargetGroupArn: !Ref LBTargetGroup + NetworkConfiguration: + AwsvpcConfiguration: + AssignPublicIp: "ENABLED" + SecurityGroups: + - !Ref ServiceSecurityGroup + Subnets: + - Ref: PublicSubnetOne + - Ref: PublicSubnetTwo + TaskDefinition: !Ref TaskDefinition + +Outputs: + WebAppLB: + Description: Web Application Load Balancer + Value: !Join [ "", [ 'http://', !GetAtt ECSALB.DNSName ] ] + Export: + Name: !Sub ${Name}-LB diff --git a/13-ECS/Practice-13.3/parameter.json b/13-ECS/Practice-13.3/parameter.json new file mode 100644 index 00000000..36e2328c --- /dev/null +++ b/13-ECS/Practice-13.3/parameter.json @@ -0,0 +1,6 @@ +[ + { + "ParameterKey": "Name", + "ParameterValue": "desmond-cluster" + } +] From 4c290c2915feb2f259a85e1483ee45653ab40da7 Mon Sep 17 00:00:00 2001 From: Dezo2018 Date: Tue, 4 Oct 2022 12:33:32 -0400 Subject: [PATCH 5/5] ecs ec2-launch type --- 13-ECS/Practice-13.2/ecs-ec2.yml | 356 +++++++++++++++++++++++++++ 13-ECS/Practice-13.2/parameter.json | 6 + 13-ECS/Practice-13.3/ecs-fargate.yml | 5 +- 3 files changed, 366 insertions(+), 1 deletion(-) create mode 100644 13-ECS/Practice-13.2/ecs-ec2.yml create mode 100644 13-ECS/Practice-13.2/parameter.json diff --git a/13-ECS/Practice-13.2/ecs-ec2.yml b/13-ECS/Practice-13.2/ecs-ec2.yml new file mode 100644 index 00000000..7769a129 --- /dev/null +++ b/13-ECS/Practice-13.2/ecs-ec2.yml @@ -0,0 +1,356 @@ +Description: An ECS EC2 Cluster + +Parameters: + Name: + Description: Name of the Repository + Type: String + LatestAmiId: + Description: Region specific image from the Parameter Store + Type: 'AWS::SSM::Parameter::Value' + Default: '/aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id' + InstanceType: + Description: Amazon EC2 instance type for the instances + Type: String + AllowedValues: [t2.micro, t2.small, t2.medium, t2.large, t2.xlarge, t3.micro, t3.small, + t3.medium, t3.large, t3.xlarge, m4.large, m4.xlarge, m5.large, m5.xlarge, c4.large, + c4.xlarge, c5.large, c5.xlarge, r4.large, r4.xlarge, r5.large, r5.xlarge, i3.large, + i3.xlarge] + Default: t2.micro + DesiredCapacity: + Type: Number + Default: '1' + Description: Number of instances to launch in your ECS cluster. + MaxSize: + Type: Number + Default: '2' + Description: Maximum number of instances that can be launched in your ECS cluster. + ImageName: + Description: The name of the image in AWS ECR + Type: String + Default: ecr + ImageTag: + Type: String + Description: The image tag (e.g, 2.xx, latest) + Default: latest + +Mappings: + SubnetConfig: + VPC: + CIDR: '10.0.0.0/16' + PublicSubnet1: + CIDR: '10.0.0.0/24' + PublicSubnet2: + CIDR: '10.0.1.0/24' + +Resources: + VPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: !FindInMap ['SubnetConfig', 'VPC', 'CIDR'] + EnableDnsHostnames: true + EnableDnsSupport: true + PublicSubnetOne: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 0 + - Fn::GetAZs: {Ref: 'AWS::Region'} + VpcId: !Ref 'VPC' + CidrBlock: !FindInMap ['SubnetConfig', 'PublicSubnet1', 'CIDR'] + MapPublicIpOnLaunch: true + PublicSubnetTwo: + Type: AWS::EC2::Subnet + Properties: + AvailabilityZone: + Fn::Select: + - 1 + - Fn::GetAZs: {Ref: 'AWS::Region'} + VpcId: !Ref 'VPC' + CidrBlock: !FindInMap ['SubnetConfig', 'PublicSubnet2', 'CIDR'] + MapPublicIpOnLaunch: true + InternetGateway: + Type: AWS::EC2::InternetGateway + GatewayAttachement: + Type: AWS::EC2::VPCGatewayAttachment + Properties: + VpcId: !Ref 'VPC' + InternetGatewayId: !Ref 'InternetGateway' + PublicRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref 'VPC' + PublicRoute: + Type: AWS::EC2::Route + DependsOn: GatewayAttachement + Properties: + RouteTableId: !Ref 'PublicRouteTable' + DestinationCidrBlock: '0.0.0.0/0' + GatewayId: !Ref 'InternetGateway' + PublicSubnetOneRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PublicSubnetOne + RouteTableId: !Ref PublicRouteTable + PublicSubnetTwoRouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PublicSubnetTwo + RouteTableId: !Ref PublicRouteTable + + # ECS Cluster Resources + ECSCluster: + Type: AWS::ECS::Cluster + Properties: + ClusterName: !Sub "${Name}-arnoldrx" + LBSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: ECS Security Group + VpcId: !Ref 'VPC' + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 80 + ToPort: 80 + CidrIp: 0.0.0.0/0 + LBSecurityGroupEgress: + Type: AWS::EC2::SecurityGroupEgress + Properties: + CidrIp: 0.0.0.0/0 + Description: Allow all outbound traffic by default + IpProtocol: "-1" + GroupId: + Fn::GetAtt: + - LBSecurityGroup + - GroupId + ServiceSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: ECS/MyApp/Service/SecurityGroup + VpcId: !Ref VPC + SecurityGroupEgress: + - CidrIp: 0.0.0.0/0 + Description: Allow all outbound traffic by default + IpProtocol: "-1" + ServiceSecurityGroupIngress: + Type: AWS::EC2::SecurityGroupIngress + Properties: + IpProtocol: tcp + Description: Load balancer to target + FromPort: 80 + GroupId: + Fn::GetAtt: + - ServiceSecurityGroup + - GroupId + SourceSecurityGroupId: + Fn::GetAtt: + - LBSecurityGroup + - GroupId + ToPort: 80 + ECSALB: + Type: AWS::ElasticLoadBalancingV2::LoadBalancer + Properties: + Scheme: internet-facing + Type: application + Subnets: + - !Ref PublicSubnetOne + - !Ref PublicSubnetTwo + SecurityGroups: + - Fn::GetAtt: + - LBSecurityGroup + - GroupId + DependsOn: + - PublicRoute + LBListener: + Type: AWS::ElasticLoadBalancingV2::Listener + Properties: + DefaultActions: + - TargetGroupArn: !Ref LBTargetGroup + Type: forward + LoadBalancerArn: !Ref ECSALB + Port: 80 + Protocol: HTTP + LBTargetGroup: + Type: AWS::ElasticLoadBalancingV2::TargetGroup + Properties: + Port: 80 + Protocol: HTTP + TargetType: instance + VpcId: !Ref VPC + TaskDefTaskRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: ecs-tasks.amazonaws.com + Version: "2012-10-17" + TaskDefExecutionRole: + Type: AWS::IAM::Role + Properties: + RoleName: "TaskDefExecutionRole" + AssumeRolePolicyDocument: + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: ecs-tasks.amazonaws.com + Version: "2012-10-17" + ManagedPolicyArns: + - "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" + EC2Role: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: [ec2.amazonaws.com] + Action: ['sts:AssumeRole'] + Path: / + Policies: + - PolicyName: ecs-service + PolicyDocument: + Statement: + - Effect: Allow + Action: ['ecs:CreateCluster', 'ecs:DeregisterContainerInstance', 'ecs:DiscoverPollEndpoint', + 'ecs:Poll', 'ecs:RegisterContainerInstance', 'ecs:StartTelemetrySession', + 'ecs:Submit*', 'logs:CreateLogStream', 'logs:PutLogEvents', 'ecr:*'] + Resource: '*' + EC2InstanceProfile: + Type: AWS::IAM::InstanceProfile + Properties: + Path: / + Roles: [!Ref 'EC2Role'] + EcsServiceRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Statement: + - Effect: Allow + Principal: + Service: [ecs.amazonaws.com] + Action: ['sts:AssumeRole'] + Path: / + Policies: + - PolicyName: "ecs-service-policy" + PolicyDocument: + Statement: + - Effect: Allow + Action: [ + 'elasticloadbalancing:Describe*', + 'elasticloadbalancing:DeregisterInstancesFromLoadBalancer', + 'elasticloadbalancing:RegisterInstancesWithLoadBalancer', + 'elasticloadbalancing:RegisterTargets', + 'ec2:Describe*', + 'ec2:AuthorizeSecurityGroupIngress' + ] + Resource: '*' + ContainerInstances: + Type: AWS::EC2::LaunchTemplate + Properties: + LaunchTemplateData: + ImageId: !Ref LatestAmiId + SecurityGroupIds: + - !GetAtt LBSecurityGroup.GroupId + InstanceType: !Ref InstanceType + IamInstanceProfile: + Arn: !GetAtt EC2InstanceProfile.Arn + UserData: + Fn::Base64: !Sub | + #!/bin/bash + echo ECS_CLUSTER=${Name}-desmond >> /etc/ecs/ecs.config; + ECSAutoScalingGroup: + Type: AWS::AutoScaling::AutoScalingGroup + Properties: + AutoScalingGroupName: "ASG" + VPCZoneIdentifier: + - Ref: PublicSubnetOne + - Ref: PublicSubnetTwo + LaunchTemplate: + LaunchTemplateId: !Ref ContainerInstances + Version: !GetAtt ContainerInstances.LatestVersionNumber + MinSize: '0' + MaxSize: !Ref MaxSize + DesiredCapacity: !Ref DesiredCapacity + ECSCluster: + Type: AWS::ECS::Cluster + DependsOn: + - CapacityProvider + Properties: + ClusterName: !Sub "${Name}-desmond" + CapacityProviders: + - !Ref CapacityProvider + Tags: + - Key: "Name" + Value: "desmond.ndambi.labs" + CapacityProvider: + Type: AWS::ECS::CapacityProvider + Properties: + Name: "CapacityProvider" + AutoScalingGroupProvider: + AutoScalingGroupArn: !Ref ECSAutoScalingGroup + ManagedScaling: + MaximumScalingStepSize: 5 + MinimumScalingStepSize: 1 + Status: ENABLED + TargetCapacity: 100 + TaskDefinition: + Type: AWS::ECS::TaskDefinition + Properties: + RequiresCompatibilities: + - "EC2" + ContainerDefinitions: + - Name: "nginx" + Image: !Sub "${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/${ImageName}:${ImageTag}" + Cpu: "128" + PortMappings: + - ContainerPort: "80" + Protocol: "tcp" + HostPort: "80" + Memory: "256" + Essential: "true" + ExecutionRoleArn: !Ref TaskDefExecutionRole + NetworkMode: "bridge" + Cpu: "256" + Memory: "512" + RuntimePlatform: + { + "OperatingSystemFamily": "LINUX", + "CpuArchitecture": "X86_64" + } + ECSService: + Type: AWS::ECS::Service + DependsOn: + - ECSALB + - LBListener + - ECSCluster + Properties: + ServiceName: "ECSService" + Cluster: !Ref ECSCluster + HealthCheckGracePeriodSeconds: 200 + DeploymentConfiguration: + DeploymentCircuitBreaker: + { + "Enable" : "true", + "Rollback" : "true" + } + MaximumPercent: "200" + MinimumHealthyPercent: "100" + DesiredCount: "1" + LoadBalancers: + - ContainerName: "nginx" + ContainerPort: "80" + TargetGroupArn: !Ref LBTargetGroup + TaskDefinition: !Ref TaskDefinition + Role: !Ref EcsServiceRole + +Outputs: + WebAppLB: + Description: Web Application Load Balancer + Value: !Join [ "", [ 'http://', !GetAtt ECSALB.DNSName ] ] + Export: + Name: !Sub ${Name}-LB + diff --git a/13-ECS/Practice-13.2/parameter.json b/13-ECS/Practice-13.2/parameter.json new file mode 100644 index 00000000..98c83e13 --- /dev/null +++ b/13-ECS/Practice-13.2/parameter.json @@ -0,0 +1,6 @@ +[ + { + "ParameterKey": "Name", + "ParameterValue": "ecs" + } +] diff --git a/13-ECS/Practice-13.3/ecs-fargate.yml b/13-ECS/Practice-13.3/ecs-fargate.yml index a94a3822..0ec2138e 100644 --- a/13-ECS/Practice-13.3/ecs-fargate.yml +++ b/13-ECS/Practice-13.3/ecs-fargate.yml @@ -82,7 +82,10 @@ Resources: ECSCluster: Type: AWS::ECS::Cluster Properties: - ClusterName: !Sub "${Name}-arnoldrx" + ClusterName: !Sub "${Name}-desmond" + Tags: + - Key: "Name" + Value: "desmond.ndambi.labs" LBSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: